Issue
Using add_url_rule fails but @app.route('') works fine.
Hello, I am trying to add SSE (Server Sent Events) to a Python Flask app. Unfortunately the app uses SOMEOBJECT.app.add_url_rule
to manage routes, so using the decorators doesn't work for me in this case.
from flask import Flask, Response
import random
import time
app = Flask(__name__)
def eventStream():
# will send simple SSE style responses
while True:
waittt = random.random()
time.sleep(waittt)
yield "data: {}\n\n".format(str(waittt))
# This route works fine :)
@app.route("/streamroute")
def stream():
return Response(eventStream(), mimetype="text/event-stream")
# This route doesn't work :(
app.add_url_rule("/stream", stream)
app.run(debug=True)
OK curl http://localhost:5000/streamroute
KO curl http://localhost:5000/stream
Solution
from flask import Flask, Response
import random
import time
app = Flask(__name__)
def eventStream():
# will send simple SSE style responses
while True:
waittt = random.random()
time.sleep(waittt)
yield "data: {}\n\n".format(str(waittt))
# This route works fine :)
@app.route('/streamroute')
def stream():
return Response(eventStream(), mimetype="text/event-stream")
# This route doesn't work :(
app.add_url_rule('/stream', 'stream', stream)
app.run(debug=True)
See the docs below, the correct syntax is:
app.add_url_rule('/stream', 'stream', stream)
For more: https://flask.palletsprojects.com/en/2.0.x/api/#flask.Flask.add_url_rule
Answered By - wgwz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.