I can’t seem to figure out how to using Flask’s streaming. Here’s my code:
@app.route('/scans/')
def scans_query():
url_for('static', filename='.*')
def generate():
yield render_template('scans.html')
for i in xrange(50):
sleep(.5)
yield render_template('scans.html', **locals())
return Response(stream_with_context(generate()))
and in my template:
<p>{% i %}</p>
I would like to see a counter on the page that changes every half second. Instead, the closest I’ve gotten is the page printing out each number on the next line.
To replace existing content on the page you might need javascript i.e., you could send it or make it to make requests for you, use long polling, websockets, etc. There are many ways to do it, here’s one that uses server send events:
Where
static/index.html:The browser reconnects by default in 3 seconds if the connection is lost. if there is nothing more to send the server could return 404 or just send some other than
'text/event-stream'content type in response to the next request. To stop on the client side even if the server has more data you could callsource.close().Note: if the stream is not meant to be infinite then use other techniques (not SSE) e.g., send javascript snippets to replace the text (infinite
<iframe>technique):I’ve inlined the html here to show that there is nothing more to it (no magic). Here’s the same as above but using templates:
Where
templates/index.html: