使用 asyncio 时如何访问字典键?

How can I access dict key while using asyncio?

这是一个简单的程序,用于从 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())

我正在接收消息并将类型更改为使用 json.loads(resp) 的口述。我的问题是如何访问字典值,因为 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())