elm*_*lmo 6 python wsgi werkzeug flask eventsource
在flask中,我有一个用于EventSource接收更新/事件的页面。
它以相当简单的方式实现:
@route('/updates')
def updates():
def gen():
while True:
update = make_update()
yield "data: {0}\n\n".format(json.dumps(update))
return Response(stream_with_context(gen()), mimetype="text/event-stream")
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是,每次我重新加载连接EventSource到“更新”页面的页面时,它都会创建一个新线程来满足该“更新”请求。而且它永远不会死。
正在进行更新,因此这意味着它将数据推送到某个地方,从而使我的服务器使用越来越多的线程以及越来越多的内存。
我希望获得的简单解决方案是while True用某种形式的替换while is_connected()。
但是我似乎找不到找到检测浏览器是否仍处于连接状态的方法。
问题:如何在发生器内部检查连接是否仍然有效?
编辑
浏览代码似乎应该调用close()generator,因此从理论上讲它应该GeneratorExit在my中的某个位置抛出gen()。
但是,我看不到有任何发生的痕迹,并且每次调用时,我都会看到pstree在每次请求/连接后又产生一个条目/updates。
小智 0
您是否尝试捕获 GeneratorExit 异常?
@app.route('/updates')
def updates():
def gen():
try:
while True:
update = make_update()
yield "data: {0}\n\n".format(json.dumps(update))
except GeneratorExit:
print("Client disconnected")
return Response(stream_with_context(gen()), mimetype="text/event-stream")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |