首页 > 解决方案 > 如何在 python web socket-client 库中使用 async on_message 函数?

问题描述

在 python 中使用 websocket-client 库时,on_message 函数是否可以成为协程?

我有以下代码:

async def on_message(ws, message):
    await get_balance() # runs an aiohttp get request
ws = websocket.WebSocketApp(data_feed,on_message=on_message)
ws.run_forever()

这给了我错误

 RuntimeWarning: coroutine 'on_message' was never awaited
  callback(self, *args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

我错过了什么吗?

提前致谢

标签: pythonasynchronouswebsocket

解决方案


websocket-client有点过时了 您可能希望将python-binance库版本至少更新到 1.0.12 以上,并使用AsyncClient内置库来执行异步操作。

from binance import AsyncClient, BinanceSocketManager

async def on_message(res):
   # strategy

async def kline_listener(client):
    bm = BinanceSocketManager(client)
    async with bm.kline_socket(symbol='ETHBTC') as stream:
        while True:
            res = await stream.recv()
            print(res)
            # do as you'd do in on_message() or just call on_message()
            await on_message(res)

async def main():
    client = await AsyncClient.create(api_key, secret, tld)
    await kline_listener(client)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

参考:


推荐阅读