Python Flask,如何检测SSE客户端与前端Java脚本断开连接 [英] Python Flask, how to detect a SSE client disconnect from front end Javascript
问题描述
也许这是Flask中的问题,无法在服务器端处理断开连接事件.
Maybe this is a problem in Flask, there is no way to handle disconnection event on the server side.
在Response类中,有一个名为"call_on_close"的方法,我们可以在其中添加不带参数的函数,例如on_close(),将在调用响应对象的close方法时将其触发,但是当我从Javascript的客户端调用EventSource.close()时,不会发生这种情况.
In Response class, there is a method named "call_on_close", where we can add a function without argument, e.g. on_close(), it will be fired when the response object's close method called, but this doesn't happen when I call EventSource.close() from the client side in Javascript.
服务器端代码:
from flask import Response
r = Response(stream(), ...)
r.call_on_close(on_close)
return r
def on_close():
print "response is closed!"
def stream():
... # subscribe to redis
for message in pubsub.listen():
....
yield 'data: %s\n\n' % message
在客户端:将卸载处理程序添加到具有SSE的页面
on client side: add unload handler to page with SSE
$(window).unload(
function() {
sse.close();
}
}
有什么问题吗?
任何建议或带有代码的解决方案都将受到赞赏!
Any suggestions or solution with code is appreciated!
提前谢谢!
推荐答案
生成器收到GeneratorExit
异常,并且在该时间您将知道它将退出.例如:
The generator receives a GeneratorExit
exception, and that's when you know it will exit. For example:
def stream():
try:
i = 0
while True:
yield 'Hello {}!'.format(i)
i += 1
time.sleep(1)
finally:
# Called after a GeneratorExit, cleanup here
i = 0
@app.route('/messages')
def messages():
return Response(stream(), content_type='text/event-stream')
将产生无限的"Hello!"
流,您将知道完成后在哪里可以运行清除代码.如果您的生成器阻塞了线程,则需要以某种方式(可能是推动虚拟项)将其解除阻塞,以便可以关闭生成器.
Will yield a infinite stream of "Hello!"
, and you will know when it's done, where you can run cleanup code. If your generator blocks the thread, it will need to be unblocked in some way (maybe pushing a dummy item) so that the generator can be closed.
这篇关于Python Flask,如何检测SSE客户端与前端Java脚本断开连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!