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

问题描述

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

我有一个函数,它通过在 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': 无,'id': 'curltest'}

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

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

我得到了这个结果:

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

我尝试了各种测试,发现添加时出现错误

data = str(data)

那么如何将函数参数传递给 this 而不出现解析错误

解决方法

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

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

注意字符串表示中的key和value是用单引号封装的。然而,JSON requires strings to be encapsulated by double quotes.

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