使用add_url_rule失败但@ app.route('')工作正常。
您好,我正在尝试将SSE(服务器发送事件)添加到Python Flask应用程序中。不幸的是,该应用使用var Feed = function (props) {
return <div>{ props.username }</div>
}
来管理路线,因此在这种情况下使用装饰器并不适合我。
SOMEOBJECT.app.add_url_rule
确定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)
答案 0 :(得分:3)
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)
请参阅下面的文档,正确的语法是:
app.add_url_rule('/stream', 'stream', stream)
更多信息:http://flask.pocoo.org/docs/0.10/api/#flask.Flask.add_url_rule