【问题标题】:python asyncio result not set in task errorpython asyncio结果未在任务错误中设置
【发布时间】:2021-12-20 03:13:33
【问题描述】:

我正在尝试创建一个asyncio 任务,执行一些db query,然后是一个for loop 进程,并将结果返回到task。但是,在下面的代码示例中,我的 result 似乎没有被放到 total_result.result() 中,而是被放到 total_result 中。

不确定我对下面asyncio 的实现是否有任何误解?

class DatabaseHandler:
    def __init__(self):
        self.loop = get_event_loop()
        self.engine = create_engine("postgres stuffs here")
        self.conn = self.engine.connect()

    async def _fetch_sql_data(self, query):
        return self.conn.execute(query)

    async def get_all(self, item):
        total_result = []
        if item == "all":
            data = create_task(self._fetch_sql_data("select col1 from table1;"))
        else:
            data = create_task(self._fetch_sql_data(f"select col1 from table1 where quote = '{item}';"))
        await data
        for i in data.result().fetchall():
            total_result.append(i[0])

        return total_result

    async def update(self):
        total_result = create_task(self.get_all("all"))
        print(await total_result)  # prints out the result immediately and not the task object.
        
        # this means that `total_result.result()` produces an error

loop = get_event_loop()
a = DatabaseHandler()
loop.run_until_complete(a.update())

我感觉这是因为total_result 是一个列表对象。但不知道如何解决。

【问题讨论】:

    标签: python python-asyncio


    【解决方案1】:

    task.result() 返回任务的结果(包装后的 coro 的返回值),而不是另一个 Task。这意味着这个

    task = asyncio.create_task(coro())
    await task
    result = task.result()
    

    实际上等价于

    result = await coro()
    

    如果您想同时执行多个协程,使用任务特别有用。但是由于您在这里没有这样做,因此您的代码有点过于复杂。你可以这样做

    async def get_all(self, item):
            total_result = []
            if item == "all":
                result = await self._fetch_sql_data("select col1 from table1;")
            else:
                result = await self._fetch_sql_data(f"select col1 from table1 where quote = '{item}';")
    
            for i in result.fetchall():
                total_result.append(i[0])
    
            return total_result # holds the results of your db query just as called from sync code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-04
      • 2015-06-01
      • 1970-01-01
      • 2020-03-17
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多