Skip to content

Instantly share code, notes, and snippets.

@Himenon
Last active January 20, 2024 04:06
Show Gist options
  • Save Himenon/9a4e7dd1a7e57a6da09b2b9624a737a0 to your computer and use it in GitHub Desktop.
Save Himenon/9a4e7dd1a7e57a6da09b2b9624a737a0 to your computer and use it in GitHub Desktop.
Simple Flask Streaming Server Example
from flask import Flask, Response, stream_with_context, request
import time
app = Flask(__name__)
# ================= Basic Streaming =================
@app.route('/hello-world')
def hello_world():
comments = [
'Hello',
'Flask',
'Stream',
'Server!',
]
def generate():
for comment in comments:
yield '<li>' + comment + '</li>'
time.sleep(0.5) # 動作をわかりやすくするために追加
return Response(generate())
# ================= Jinja2 を使った Streaming =================
def stream_template(template_name, **context):
app.update_template_context(context)
t = app.jinja_env.get_template(template_name)
rv = t.stream(context)
rv.enable_buffering(5)
for buffer in rv:
yield buffer
time.sleep(0.5)
@app.route('/hello-world-with-template')
def hello_world_with_template():
comments = ['Count: {}'.format(i) for i in range(20)]
return Response(stream_template('comment_list.html', comments=comments))
# ================= Streaming with Context =================
@app.route('/stream')
def streamed_response():
def generate():
yield 'Hello '
time.sleep(1)
yield request.args['name']
time.sleep(1)
yield '!'
return Response(stream_with_context(generate()))
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5001, debug=True)
<p>Start!</p>
<ul>
{% for comment in comments %}
<li>{{ comment }}</li>
{% endfor %}
</ul>
<p>Finish!</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment