在Websockets中使用Python?

时间:2018-12-06 15:53:59

标签: python

我正在监视来自Blockchain.info API的未确认交易。这是我的Python代码:

import json
from websocket import create_connection

ws = create_connection("wss://ws.blockchain.info/inv")
ws.send("""{"op":"unconfirmed_sub"}""")
while True:
    tx = ws.recv()
    data_decoded=json.loads(tx)
    hash=data_decoded['x']['hash']
    addr=data_decoded['x']['out'][0]['addr']
    print(hash)
    print(addr)

这正确连接并显示每个事务,如下所示:

{
    "op": "utx",
    "x": {
        "lock_time": 0,
        "ver": 1,
        "size": 192,
        "inputs": [
            {
                "sequence": 4294967295,
                "prev_out": {
                    "spent": true,
                    "tx_index": 99005468,
                    "type": 0,
                    "addr": "1BwGf3z7n2fHk6NoVJNkV32qwyAYsMhkWf",
                    "value": 65574000,
                    "n": 0,
                    "script": "76a91477f4c9ee75e449a74c21a4decfb50519cbc245b388ac"
                },
                "script": "483045022100e4ff962c292705f051c2c2fc519fa775a4d8955bce1a3e29884b2785277999ed02200b537ebd22a9f25fbbbcc9113c69c1389400703ef2017d80959ef0f1d685756c012102618e08e0c8fd4c5fe539184a30fe35a2f5fccf7ad62054cad29360d871f8187d"
            }
        ],
        "time": 1440086763,
        "tx_index": 99006637,
        "vin_sz": 1,
        "hash": "0857b9de1884eec314ecf67c040a2657b8e083e1f95e31d0b5ba3d328841fc7f",
        "vout_sz": 1,
        "relayed_by": "127.0.0.1",
        "out": [
            {
                "spent": false,
                "tx_index": 99006637,
                "type": 0,
                "addr": "1A828tTnkVFJfSvLCqF42ohZ51ksS3jJgX",
                "value": 65564000,
                "n": 0,
                "script": "76a914640cfdf7b79d94d1c980133e3587bd6053f091f388ac"
            }, {
                "spent": false,
                "tx_index": 99006637,
                "type": 0,
                "addr": "1oWiR4wBfdUjG1htJQBGvFE49t3PFcWLE",
                "value": 65564000,
                "n": 0,
                "script": "76a914640cfdf7b79d94d1c980133e3587bd6053f091f388ac"
            }, {
                "spent": false,
                "tx_index": 99006637,
                "type": 0,
                "addr": "1GSKPwn7SnVWtX7esghyurX6y9vG5EbW5i",
                "value": 65564000,
                "n": 0,
                "script": "76a914640cfdf7b79d94d1c980133e3587bd6053f091f388ac"
            }
        ]
    }
}

但是现在,它仅显示['x']['hash']和第一个['x']['out']['addr']中的数据,而不是在示例中有多个像这样的情况下打印所有addr

如何获取所有['x']['out']['addr']的打印内容?

1 个答案:

答案 0 :(得分:0)

exports.handler = async (event) => {
  context.callbackWaitsForEmptyEventLoop = false
  const db = await connect()
  await db.write(data)
  return { ok: true }
}

编辑:因此,我在下面的评论之后对此进行了测试,并且不需要json.loads。这有效:

hash=your_json['x']['hash']
addr=your_json['x']['out]['addr']

此外,要访问嵌套列表中的所有地址,您将需要遍历它们:

print(x['x']['hash'])
>>>0857b9de1884eec314ecf67c040a2657b8e083e1f95e31d0b5ba3d328841fc7f