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()
是一个同步接口;要在不阻塞的情况下使用它,您需要执行以下两项操作之一:
- 将其重写为异步。您无法真正使
方法异步,因此需要将内容重构为静态工厂函数,而不是构造函数。在大多数情况下,只有当方法依赖于网络I/O(而不是从文件系统读取或在CPU上处理结果)时,此路径才有意义\uuuu init\uuuu
- 在工作线程上运行它,并在主线程上异步等待其结果。从你提出问题的方式来看,这似乎是适合你的正确方法。我推荐使用
包(自Python 3.2以来一直在标准库中;可通过concurrent.futures
for 2.x获得)pip install futures
@tornado.gen.coroutine
def get(self, id):
data = yield executor.submit(MyDataFrame, id)
self.write(data.getFoo())
其中,
executor
是需要在MyDataFrame
中实现的ThreadPoolExecutor的全局实例,其构造函数可能需要完全重写,以便利用Tornado的事件循环而不是阻塞。