【问题标题】:How to use async on_message function with python web socket-client library?如何在 python web socket-client 库中使用 async on_message 函数?
【发布时间】:2021-03-27 00:56:17
【问题描述】:

在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

我错过了什么吗?

提前致谢

【问题讨论】:

    标签: python asynchronous websocket


    【解决方案1】:

    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())
    

    参考:

    【讨论】:

      猜你喜欢
      • 2020-04-13
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2021-04-11
      • 2020-08-01
      相关资源
      最近更新 更多