In Sanic (python async web framework) I can create stream object output to html with this:
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')
Result:
foo bar
And with Jinja2 I can render asynchronously like so after turn on the async feature:
from sanic.response import html
@app.route('/')
async def test(request):
rendered_template = await template.render_async(
key='value')
return html(rendered_template)
I tried with this to output stream object to Jinja2 template:
@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
but all I got was the downloaded template (html file).
I there any way to rig Jinja2 template.render_async
to accept Sanic's response.write
and return it in stream?
After tweaking, here's what I came up with:
And here's the Jinja2 template: