使用 Pyramid 的服务器发送事件 - 如何检测与客户端的连接是否已丢失
Server Sent Events with Pyramid - How to detect if the connection to the client has been lost
我有一个发送 SSE 消息的金字塔应用程序。它基本上像这样工作:
def message_generator():
for i in range(100):
print("Sending message:" + str(i))
yield "data: %s\n\n" % json.dumps({'message': str(i)})
time.sleep(random.randint(1, 10))
@view_config(route_name='events')
def events(request):
headers = [('Content-Type', 'text/event-stream'),
('Cache-Control', 'no-cache')]
response = Response(headerlist=headers)
response.app_iter = message_generator()
return response
当我浏览到 /events 时,我得到了事件。当我移动到另一个页面时,事件停止,当我关闭浏览器时,事件停止。
例如,如果我在 /events 中并关闭计算机,就会出现问题。服务器不知道客户端迷路了,message_generator一直向虚空发送消息。
在此页面中:A Look at Server-Sent Events提及此内容:
...the server should detect this (when the client stops) and stop
sending further events as the client is no longer listening for them.
If the server does not do this, then it will essentially be sending
events out into a void.
有没有办法用 Pyramid 检测到这个?我试过
request.add_finished_callback()
但是这个回调似乎是用
调用的
return response
我使用 Gunicorn 和 gevent 来启动服务器。
非常感谢任何想法
来自 PEP 3333:
Applications returning a generator or other custom iterator should not assume the entire iterator will be consumed, as it may be closed early by the server.
基本上,当客户端断开连接时,WSGI 服务器 "should" 调用 app_iter
上的 close()
方法(所有生成器,例如您的示例,自动支持此)。但是,不需要服务器来执行此操作,而且似乎许多 WSGI 服务器都不需要。例如,您提到了 gunicorn(我尚未独立验证),但我确实验证了女服务员也没有。结果,我在女服务员上打开了 [1],并且一直在进行修复。 WSGI 环境中的流式响应充其量是不稳定的并且通常取决于服务器。例如,在女服务员上,您需要设置 send_bytes=0
以避免它缓冲响应数据。
我有一个发送 SSE 消息的金字塔应用程序。它基本上像这样工作:
def message_generator():
for i in range(100):
print("Sending message:" + str(i))
yield "data: %s\n\n" % json.dumps({'message': str(i)})
time.sleep(random.randint(1, 10))
@view_config(route_name='events')
def events(request):
headers = [('Content-Type', 'text/event-stream'),
('Cache-Control', 'no-cache')]
response = Response(headerlist=headers)
response.app_iter = message_generator()
return response
当我浏览到 /events 时,我得到了事件。当我移动到另一个页面时,事件停止,当我关闭浏览器时,事件停止。
例如,如果我在 /events 中并关闭计算机,就会出现问题。服务器不知道客户端迷路了,message_generator一直向虚空发送消息。
在此页面中:A Look at Server-Sent Events提及此内容:
...the server should detect this (when the client stops) and stop sending further events as the client is no longer listening for them. If the server does not do this, then it will essentially be sending events out into a void.
有没有办法用 Pyramid 检测到这个?我试过
request.add_finished_callback()
但是这个回调似乎是用
调用的return response
我使用 Gunicorn 和 gevent 来启动服务器。
非常感谢任何想法
来自 PEP 3333:
Applications returning a generator or other custom iterator should not assume the entire iterator will be consumed, as it may be closed early by the server.
基本上,当客户端断开连接时,WSGI 服务器 "should" 调用 app_iter
上的 close()
方法(所有生成器,例如您的示例,自动支持此)。但是,不需要服务器来执行此操作,而且似乎许多 WSGI 服务器都不需要。例如,您提到了 gunicorn(我尚未独立验证),但我确实验证了女服务员也没有。结果,我在女服务员上打开了 [1],并且一直在进行修复。 WSGI 环境中的流式响应充其量是不稳定的并且通常取决于服务器。例如,在女服务员上,您需要设置 send_bytes=0
以避免它缓冲响应数据。