我有一个提供网络套接字的课程,并听 PostgreSQL。使用 asyncpg,当我尝试使用 add_listener 时,出现错误:RuntimeWarning: coroutine was never awaited。如何异步/等待回调。我尝试添加“等待 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()