• Now all data be ready for publish, We had made our blog alive now. Haha.

  • These days CCP GFW blocked all the IPs from US and when I switch my IP in google Cloud, the disk data cannot be restore again. I have to restart my blog totally, Now the website is still building…

Display data streamed from a Flask view as it updates- Stack Overflow

Python PingBook 2 months ago (10-23) 18 0


I have a view that generates data and streams it in real time. I can’t figure out how to send this data to a variable that I can use in my HTML template. My current solution just outputs the data to a blank page as it arrives, which works, but I want to include it in a larger page with formatting. How do I update, format, and display the data as it is streamed to the page?

import flask
import time, math

app = flask.Flask(__name__)

def index():
def inner():
# simulate a long process to watch
for i in range(500):
j = math.sqrt(i)
# this value should be inserted into an HTML template
yield str(i) + ‘
return flask.Response(inner(), mimetype=’text/html’)



You can stream data in a response, but you can’t dynamically update a template the way you describe. The template is rendered once on the server side, then sent to the client. You’ll need to use JavaScript to read the streamed response and output the data on the client side.

Use XMLHttpRequest to make a request to the endpoint that will stream the data. Then periodically read from the stream until it is done.

This example assumes a very simple message format: a single line of data, followed by a newline. You can of course get as complicated in parsing as you like, as long as there’s a way to identify each message. For example, you could return a JSON object and decode it on the client.

from time import sleep
from flask import Flask, render_template
from math import sqrt

app = Flask(__name__)

def index():
# render the template (below) that will use JavaScript to read the stream
return render_template(‘index.html’)

def stream():
def generate():
for i in range(500):
yield ‘{}\n’.format(sqrt(i))

return app.response_class(generate(), mimetype=’text/plain’)


This is the latest output:

This is all the output:

    Copyright from PingBook Blog, If not specified, they are original. This site uses BY-NC-SAProtocol authenticated.
    For reprinting, please indicate the link of the original text:Display data streamed from a Flask view as it updates- Stack Overflow
    LIKE (0)
    SHARE (0)
    We create, We sharing! Tag every value data your sharing
    Submit comments
    Cancel comments
    emoji picture bold strikethrough center italic check in

    Hi,you need to provide your name and email adress!

    • Name (Required)
    • Email (Required)
    • Website