我们现在正在将代码从旋风转移到龙卷风。之前,我们在cyclone中使用@cyclone.web.asynchronous来实现非阻塞异步调用(这样我们就不会阻塞UI)。在tornado中的替代方案是什么,@tornado.web.asynchronous在tornado 6.1中不工作。我的cyclone代码是这样的:
class ABCHandler(cyclone.web.RequestHandler):
@cyclone.web.asynchronous
def post(self):
some_validation()
# Spawn a thread to import the files and leave the post method
# asynchronous decorator will keep the request open to write the response on,
# once the import is complete
file_handler.start() ---- this is a thread that do all the heavy work and in this method we are
closing the request with self.finish
Class file_handler():
run(self):
{
---do some heavy work, like importing a file
self.importing_a_large_file()
self.set_status(status)
self.write(json_response)
self.finish()
} 什么是它的龙卷风等效法。
我尝试了各种方法,比如添加gencouroutine装饰器,将方法名改为async,但似乎都不起作用。
发布于 2021-01-18 19:44:33
使用Python的async def协程。
你不能在Tornado中使用常规线程,所以你必须使用run_in_executor方法。它将在单独的线程中运行代码,但允许您在不阻塞的情况下等待结果。
class ABCHandler(tornado.web.RequestHandler):
async def post(self):
loop = tornado.ioloop.IOLoop.current()
some_data = await loop.run_in_executor(executor=None, func=blocking_func)
self.write(some_data)
# this is a blocking code
# you don't have to create a separate thread for this
# because `run_in_executor` will take care of that.
def blocking_func():
# do blocking things here
return some_data发布于 2021-01-18 23:02:29
听起来cyclone.web.asynchronous等同于tornado.web.asynchronous,所以首先从cyclone迁移到Tornado5.1(仍然支持asynchronous装饰器)可能会更好,然后在单独的步骤中迁移到协程和Tornado6.x。(或者,如果cyclone支持协程,则在切换到Tornado之前,在cyclone上移动到协程)。
如果你试图在一次跳跃中从cyclone.web.asynchronous迁移到带有本机协程的Tornado6,这将是一个非常困难的重构。而且,您的示例代码看起来像是从另一个线程调用像RequestHandler.finish这样的方法。我不确定在旋风中是否允许这样做,但在龙卷风中肯定不允许。
https://stackoverflow.com/questions/65770613
复制相似问题