0

在 Sanic(python 异步 Web 框架)中,我可以使用以下命令创建流对象输出到 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')

结果:

富吧

使用 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 文件)。

我有什么办法可以让 Jinja2template.render_async接受 Sanicresponse.write并在流中返回它?

4

1 回答 1

0

调整后,这是我想出的:

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>
于 2018-11-25T13:50:41.053 回答