异步对象实例化

2024-10-02 06:35:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

class IndexHandler(tornado.web.RequentHandler):
    def get(self, id):
        # Async the following
        data = MyDataFrame(id)
        self.write(data.getFoo())

MyDataFrame返回一个pandasDataFrame对象,根据它要分析的文件,可能需要一些时间。在


Tags: the对象实例selfwebiddataget
1条回答
网友
1楼 · 发布于 2024-10-02 06:35:52

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

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

  • 在工作线程上运行它,并在主线程上异步等待结果。从你提出问题的方式来看,这听起来对你来说是正确的方法。我建议使用concurrent.futures包(在python3.2之后的标准库中;可通过2.x的pip install futures获得)。

这看起来像:

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

其中executorThreadPoolExecutor的全局实例。在

相关问题 更多 >

    热门问题