如何在 Python/Tornado 中等待调用 request.finish()
How to wait for the calling of request.finish() in Python/Tornado
在我的 python 文件中,我有两个处理程序 classes:MainHandler(tornado.web.RequestHandler) 和 WebSocketHandler(tornado.web.WebSocketHandler)。在 MainHandler class 中,我在 get 方法中执行以下代码:
class MainHandler(tornado.web.RequestHandler):
#some code
def get(self):
#some code
mainHandler_dict[chan] = self
await self.finish() #line of code that would do the waiting somehow
所以我将请求存储在全局字典中,这样我就可以在 WebSocketHandler 的 on_message
方法中调用 request.write()
和 request.finish()
class:
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def on_message(self, message):
#some code
request.write(body)
request.finish()
我从全局字典中获取"request"变量并尝试调用write(),但出现了以下错误:RuntimeError: Cannot write() after finish()
我认为finish()
是在MainHandlerclass中的get方法结束后自动调用的。
那么有没有办法让 requestHandler 保持 "waiting" 而我不通过文件的某个地方调用 request.finish()
?
你可能应该反过来处理这个问题;不要存储 "the request",尝试以某种方式让它保持活动状态,并从其他地方写入它,而是让请求处理程序等待您需要的值变得可用。例如:
class MainHandler(RequestHandler):
async def get(self):
value = await magic()
self.write(value)
现在,如何处理“magic
”部分在一定程度上取决于该值的来源以及您可以使用的内容,但让我们用一个简单的 Future
:
来说明
async def get(self):
futures[chan] = asyncio.Future()
value = await futures[chan]
self.write(value)
其他地方:
futures[chan].set_result(42)
在我的 python 文件中,我有两个处理程序 classes:MainHandler(tornado.web.RequestHandler) 和 WebSocketHandler(tornado.web.WebSocketHandler)。在 MainHandler class 中,我在 get 方法中执行以下代码:
class MainHandler(tornado.web.RequestHandler):
#some code
def get(self):
#some code
mainHandler_dict[chan] = self
await self.finish() #line of code that would do the waiting somehow
所以我将请求存储在全局字典中,这样我就可以在 WebSocketHandler 的 on_message
方法中调用 request.write()
和 request.finish()
class:
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def on_message(self, message):
#some code
request.write(body)
request.finish()
我从全局字典中获取"request"变量并尝试调用write(),但出现了以下错误:RuntimeError: Cannot write() after finish()
我认为finish()
是在MainHandlerclass中的get方法结束后自动调用的。
那么有没有办法让 requestHandler 保持 "waiting" 而我不通过文件的某个地方调用 request.finish()
?
你可能应该反过来处理这个问题;不要存储 "the request",尝试以某种方式让它保持活动状态,并从其他地方写入它,而是让请求处理程序等待您需要的值变得可用。例如:
class MainHandler(RequestHandler):
async def get(self):
value = await magic()
self.write(value)
现在,如何处理“magic
”部分在一定程度上取决于该值的来源以及您可以使用的内容,但让我们用一个简单的 Future
:
async def get(self):
futures[chan] = asyncio.Future()
value = await futures[chan]
self.write(value)
其他地方:
futures[chan].set_result(42)