python - 使用 asyncio 时如何访问 dict 键?
问题描述
这是一个简单的程序,用于从 Binance 交易所检索多对烛台数据。我发现它可以用 asyncio 包来完成。
import websockets
import asyncio
import json
import pprint
async def candle_stick_data():
url = "wss://stream.binance.com:9443/ws/" #steam address
first_pair = 'xlmbusd@kline_1m' #first pair
async with websockets.connect(url+first_pair) as sock:
pairs = '{"method": "SUBSCRIBE", "params": ["xlmbnb@kline_1m","bnbbusd@kline_1m" ], "id": 1}' #other pairs
await sock.send(pairs)
print(f"> {pairs}")
while True:
resp = await sock.recv()
resp=json.loads(resp)
pprint.pprint(resp)
candle = resp['k']
asyncio.get_event_loop().run_until_complete(candle_stick_data())
我收到消息并将类型更改为 dict with json.loads(resp)
。我的问题是如何访问 dict 值,因为candle = resp['k']
会导致“键错误'k'”。我是 asyncio 的新手,也许我根本不需要它来检索几对数据。
更新消息截图
解决方案
您的第一条传入消息在字典中确实没有“k”键。
我刚刚if else
在您的代码中添加了块,它运行良好:
import websockets
import asyncio
import json
import pprint
async def candle_stick_data():
url = "wss://stream.binance.com:9443/ws/" #steam address
first_pair = 'xlmbusd@kline_1m' #first pair
async with websockets.connect(url+first_pair) as sock:
pairs = '{"method": "SUBSCRIBE", "params": ["xlmbnb@kline_1m","bnbbusd@kline_1m" ], "id": 1}' #other pairs
await sock.send(pairs)
print(f"> {pairs}")
while True:
resp = await sock.recv()
resp = json.loads(resp)
# get 'k' key value if it exits, otherwise None
k_key_val = resp.get('k', None)
# easy if else block
if not k_key_val:
print(f"No k key found: {resp}")
else:
pprint.pprint(k_key_val)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(candle_stick_data())
推荐阅读
- swift - UICollectionView 单元格复用和在线图片
- python - 带有 Qlabel 和 signal&slot 的 Qcombobox
- regex - 如何通过终端重命名一堆文件,保留文件名的前缀和后缀并删除中间的通配符?
- amazon-web-services - aws api 网关和 lambda 返回新的错误状态
- apache-spark - 使用火花流消费 kafka 主题
- c# - 将 C# 多行字符串文字写入文件和 CRLF 行结尾
- c# - 如何将控制台应用程序文本写入 txt
- macos - 使 MFC 应用程序能够识别 Mac OS X
- python-sphinx - 如何在 sphinx rst 文档中写不等号
- sql-server - EC2 上的 SQL Server - 无法在 SSMS 中使用 SQL Server 身份验证