【问题标题】:How can I access dict key while using asyncio?使用 asyncio 时如何访问 dict 键?
【发布时间】:2021-03-19 18:15:36
【问题描述】:

这是一个简单的程序,用于从 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) 的字典。我的问题是如何访问 dict 值,因为candle = resp['k'] 导致“密钥错误'k'”。我是 asyncio 的新手,也许我根本不需要它来检索几对数据。

更新消息截图

【问题讨论】:

  • “我收到消息”。什么消息?
  • 您正在打印出resp,这是一件非常好的事情。您在该打印输出中看到密钥 k 吗?
  • @Tim Roberts 看截图
  • @user15082198 我清理了您帖子中的一些格式;如果我弄错了,请更正代码块的缩进!
  • @TimRoberts 检查

标签: python python-asyncio binance


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 2018-07-27
    • 1970-01-01
    • 2012-03-08
    • 2012-01-28
    • 1970-01-01
    相关资源
    最近更新 更多