python - 如何在 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
我错过了什么吗?
提前致谢
解决方案
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())
参考:
推荐阅读
- amazon-cloudwatch - AWS CloudWatch 日志计数问题
- matlab - MATLAB:使用 For 循环绘制下标
- c# - API URL 在浏览器中有效,但在 REST 中无效。它给出“响应状态代码不表示成功:404(未找到)。”
- python - 将 retrain.py 的输出转换为 tensorflow.js
- c# - 我希望绑定到 WPF 列表中的列表
- ruby-on-rails - 如何将大类的私有方法从单个文件中移出
- go - 在 golang 项目中对 sqlx 进行查询后,数据库连接仍在使用中
- jsf - 有人在 Payara 5 / Glassfish 5 上安装了 Icefaces 3.3 应用程序吗?
- python - 将数据框中的列表元素拆分为多行
- linux - 如何删除其他用户创建的共享内存文件?