Last active
January 20, 2024 04:06
-
-
Save Himenon/9a4e7dd1a7e57a6da09b2b9624a737a0 to your computer and use it in GitHub Desktop.
Simple Flask Streaming Server Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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