首页 > 解决方案 > 使用 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 的新手,也许我根本不需要它来检索几对数据。

更新消息截图

在此处输入图像描述

标签: pythonpython-asynciobinance

解决方案


您的第一条传入消息在字典中确实没有“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())


推荐阅读