【问题标题】:RuntimeWarning: coroutine was never awaited. How to async / await a callbackRuntimeWarning:从未等待协程。如何异步/等待回调
【发布时间】:2019-12-19 00:48:38
【问题描述】:

我有一个服务于 web 套接字的类,并听 PostgreSQL。使用 asyncpg,当我尝试使用 add_listener 时,出现错误:RuntimeWarning: coroutine was never awaited。如何异步/等待回调。我尝试添加“await self.listener”,但它不起作用。

有没有办法以另一种方式处理这个问题?

import asyncio
import http
import websockets
import asyncpg

class App(object):

    def __init__(self, loop):
        self.loop = loop
        self.ws_list = []
        self.conn = None

    async def ws_handler(self, ws, path):
        if self.conn is None:
            self.conn = await asyncpg.connect(user='xxx', password='xxx', database='pgws', host='127.0.0.1')
            await self.conn.add_listener('todo_updates', self.listener)
        print('new socket!!!')
        self.ws_list.append(ws)
        while True:
            await asyncio.sleep(1)

    async def listener(self, conn, pid, channel, payload):
        print(payload)
        for ws in self.ws_list:
            task = asyncio.create_task()
            await ws.send(payload)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    app = App(loop)
    start_server = websockets.serve(app.ws_handler, 'localhost', 8766)
    app.loop.run_until_complete(start_server)
    app.loop.run_forever()

【问题讨论】:

    标签: python asynchronous python-asyncio asyncpg


    【解决方案1】:

    问题是您传递给asyncpg.Connection.add_listener() 的回调是coroutine function,但它应该是一个简单的同步函数。 asyncpg 不会引发错误,因为从技术上讲,它仍然是一个可调用的,它需要一个连接、pid、通道和有效负载,但它在被调用时的行为与您预期的不同。

    要从同步回调中​​调用异步函数(当事件循环已经在运行时),您需要使用类似asyncio.create_task()(在 Python >=3.7 中)或 loop.create_task()(在 Python >=3.4 中。 2) 或asyncio.ensure_future()(在 Python >=3.4.4 中),如下所示:

    class App:
        ...  # Your other code here
        def listener(self, conn, pid, channel, payload):
            print(payload)
            for ws in self.ws_list:
                asyncio.create_task(ws.send(payload))
    

    请注意asyncio.create_task()(和其他上述函数)将立即返回,并且不会等待任务完成。该任务将计划在其他地方的一个或多个awaits 之后运行。

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2021-10-22
      • 2019-12-15
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-10
      相关资源
      最近更新 更多