Python 异步对象实例化

Python 异步对象实例化,python,asynchronous,tornado,Python,Asynchronous,Tornado,如何使以下对象实例化异步: class IndexHandler(tornado.web.RequentHandler): def get(self, id): # Async the following data = MyDataFrame(id) self.write(data.getFoo()) MyDataFrame返回一个pandasDataFrame对象,根据需要解析的文件,可能需要一些时间 MyDataFrame()是一个同

如何使以下对象实例化异步:

class IndexHandler(tornado.web.RequentHandler):
    def get(self, id):
        # Async the following
        data = MyDataFrame(id)
        self.write(data.getFoo())
MyDataFrame
返回一个
pandas
DataFrame
对象,根据需要解析的文件,可能需要一些时间

MyDataFrame()
是一个同步接口;要在不阻塞的情况下使用它,您需要执行以下两项操作之一:

  • 将其重写为异步。您无法真正使
    \uuuu init\uuuu
    方法异步,因此需要将内容重构为静态工厂函数,而不是构造函数。在大多数情况下,只有当方法依赖于网络I/O(而不是从文件系统读取或在CPU上处理结果)时,此路径才有意义

  • 在工作线程上运行它,并在主线程上异步等待其结果。从你提出问题的方式来看,这似乎是适合你的正确方法。我推荐使用
    concurrent.futures
    包(自Python 3.2以来一直在标准库中;可通过
    pip install futures
    for 2.x获得)

这看起来像:

@tornado.gen.coroutine
def get(self, id):
    data = yield executor.submit(MyDataFrame, id)
    self.write(data.getFoo())

其中,
executor
是需要在
MyDataFrame
中实现的
ThreadPoolExecutor

的全局实例,其构造函数可能需要完全重写,以便利用Tornado的事件循环而不是阻塞。