如何允许使用 Python 中的请求将函数参数传递到 cURL 请求中

How do I allow for passage of function parameters into a cURL request using requests in Python

我正在尝试将比特币 RPC 调用转换为在 python 中使用的函数,一些 RPC API 调用具有参数,例如命令 getblockhash 的块高度。

我有一个有效的函数,returns 通过在 params 关键字中传递 [0] 来创建创世块:

def getblockhash():
    headers = {
        'content-type': 'text/plain;',
    }
    data = '{"jsonrpc": "1.0", "id":"curltest", "method": "getblockhash", "params": [0]}'
    response = requests.post('http://127.0.0.1:8332/', headers=headers, data=data,
                             auth=(USERNAME, PASSWORD))
    response = response.json()
    return response

我收到这样的回复:

{'result': '000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f', 'error': None, 'id': 'curltest'}

我希望能够将变量传递到此位置而不是对其进行硬编码,例如:

def getblockhash(height):
    headers = {
        'content-type': 'text/plain;',
    }
    data = {"jsonrpc": "1.0", "id":"curltest", "method": "getblockhash", "params": [height]}
    data = str(data)
    response = requests.post('http://127.0.0.1:8332/', headers=headers, data=data,
                             auth=(USERNAME, PASSWORD))
    response = response.json()
    return response

我得到这个结果:

"{'result': None, 'error': {'code': -32700, 'message': 'Parse error'}, 'id': None}"

我试过测试各种东西,发现添加时出现错误

data = str(data)

那么如何在不出现解析错误的情况下将函数参数传递给它呢?

您直接将字典的字符串表示形式发布到服务器。但是,字典的字符串表示无效 JSON。示例:

>>> example = {"hello": "world"}
>>> str(example)
"{'hello': 'world'}"

注意字符串表示中的键和值用单引号括起来。然而,JSON requires strings to be encapsulated by double quotes.

可能的解决方案是:使用 json kwarg 而不是 datarequests 将字典转换为有效 JSON,手动将字典转换为 JSON 使用 json 模块的数据,或者(正如 jordanm 在他们的评论中建议的那样)使用 JSON-RPC 模块。