龙卷风环境中@ cyclone.web.asynchronous的替代

托米希尔

我们现在正在将代码从飓风转移到龙卷风。以前,我们使用@ cyclone.web.asynchronous作为我们的api之一,以便在旋风分离器中不阻塞异步调用(这样就不会阻塞UI)。在龙卷风中,这有什么替代方法,@ tornado.web.asynchronous在龙卷风6.1中不起作用。我的气旋代码像这样

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 decorater,将方法名称更改为async,但似乎无济于事。

木霉

使用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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章