所以我正在做的是编写WSGI流服务,该服务利用迭代器中包含的Queue来实现多播推送.以下是该服务的简化模型:
# this is managed by another thread
def processor_runner():
generator = SerialMessageGenerator()
for message in generator:
for client in Processor.connections:
client.put(message)
# this is managed by twisted's wsgi implementation
def main(environ, start_response):
queue = Queue()
Processor.connections.append(queue)
status = '200 OK'
response_headers = [
('Content-Type', 'application/json'),
('Transfer-Encoding', 'chunked')
]
start_response(status, response_headers)
return iter(queue.get, None)
Run Code Online (Sandbox Code Playgroud)
并且这与作为WSGI服务器的扭曲效果很好(顺便说一下,串行生成器是由进程间队列连接到处理器的独立进程).我的问题是如何检测客户端何时断开连接并将其从队列中删除?我虽然将队列添加为客户端套接字的元组,即(套接字,队列),然后在执行put之前检查套接字是否仍然连接.但是,我不确切地知道从环境中获取什么.在我将某些东西放在一起之前,是否有任何人有这样做的经验?
更新
这是我最终采用的解决方案:
class IterableQueue(Queue):
def __init__(self):
Queue.__init__(self) # Queue is an old style class
ShellProcessor.connections.append(self)
def __iter__(self):
return iter(self.get, None)
def close(self):
self.put(None)
self.task_done()
ShellProcessor.connections.remove(self)
Run Code Online (Sandbox Code Playgroud)