2024-10-02 06:35:52 发布
网友
如何使以下对象实例化异步:
class IndexHandler(tornado.web.RequentHandler): def get(self, id): # Async the following data = MyDataFrame(id) self.write(data.getFoo())
MyDataFrame返回一个pandasDataFrame对象,根据它要分析的文件,可能需要一些时间。在
MyDataFrame
pandas
DataFrame
MyDataFrame()是一个同步接口;要在不阻塞的情况下使用它,需要执行以下两个操作之一:
MyDataFrame()
重写为异步。不能真正使__init__方法异步,因此需要将其重构为静态工厂函数,而不是构造函数。在大多数情况下,只有当方法依赖于网络I/O(而不是从文件系统读取数据或在CPU上处理结果)时,此路径才有意义。
__init__
在工作线程上运行它,并在主线程上异步等待结果。从你提出问题的方式来看,这听起来对你来说是正确的方法。我建议使用concurrent.futures包(在python3.2之后的标准库中;可通过2.x的pip install futures获得)。
concurrent.futures
pip install futures
这看起来像:
@tornado.gen.coroutine def get(self, id): data = yield executor.submit(MyDataFrame, id) self.write(data.getFoo())
其中executor是ThreadPoolExecutor的全局实例。在
executor
ThreadPoolExecutor
MyDataFrame()
是一个同步接口;要在不阻塞的情况下使用它,需要执行以下两个操作之一:重写为异步。不能真正使
__init__
方法异步,因此需要将其重构为静态工厂函数,而不是构造函数。在大多数情况下,只有当方法依赖于网络I/O(而不是从文件系统读取数据或在CPU上处理结果)时,此路径才有意义。在工作线程上运行它,并在主线程上异步等待结果。从你提出问题的方式来看,这听起来对你来说是正确的方法。我建议使用
concurrent.futures
包(在python3.2之后的标准库中;可通过2.x的pip install futures
获得)。这看起来像:
其中
executor
是ThreadPoolExecutor
的全局实例。在相关问题 更多 >
编程相关推荐