Как вставить объект потока Sanic в асинхронный шаблон jinja - PullRequest
0 голосов
/ 25 ноября 2018

В Sanic (асинхронная веб-среда Python) я могу создать потоковый объект для вывода в html с помощью:

from sanic.response import stream

@app.route("/")
async def test(request):
    async def sample_streaming_fn(response):
        await response.write('<b>foo</b>') 
        await response.write('<b>bar</b>')
    return stream(sample_streaming_fn, content_type='text/html')

Результат:

foo bar

А с Jinja2 я могу рендерить асинхронно так же, как после включения функции асинхронности:

from sanic.response import html

@app.route('/')
async def test(request):
     rendered_template = await template.render_async(
         key='value')
     return html(rendered_template)

Я пытался с помощью этого вывести объект потока в шаблон Jinja2:

@app.route('/')
async def test(request):
    async def stream_template(response):
        rendered_template =  await template.render_async(
            key="<b>value</b>")
        await response.write(rendered_template)
    return stream(stream_template, content_type='text/html') # I need it to return stream

, новсе, что я получил, было загруженным шаблоном (html-файл).

Есть ли способ установить Jinja2 template.render_async, чтобы принять response.write Саника и вернуть его в потоке?

1 Ответ

0 голосов
/ 25 ноября 2018

После настройки вот что я придумал:

from sanic.response import stream

@app.route("/")
async def test(request):
    async def sample_streaming_fn(response):
        await response.write(await template.render_async(key='<b>foo</b>'))
        await asyncio.sleep(1) # just for checking if it's indeed streamed
        await response.write(await template.render_async(key='<b>bar</b>'))
    return stream(sample_streaming_fn, content_type='text/html')

А вот шаблон Jinja2:

<p>{{ key|safe }}</p>
...