【问题标题】:How do I allow for passage of function parameters into a cURL request using requests in Python如何允许使用 Python 中的请求将函数参数传递到 cURL 请求中
【发布时间】:2021-01-22 21:56:18
【问题描述】:

我正在尝试将比特币 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

我收到以下回复:

{'结果':'000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f','错误':无,'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':无}"

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

数据 = str(数据)

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

【问题讨论】:

  • 您选择不使用现有 json-rpc 模块的任何原因?

标签: python curl python-requests rpc bitcoin


【解决方案1】:

您直接将字典的字符串表示形式发布到服务器。但是,字典的字符串表示不是有效的 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 模块。

【讨论】:

  • 感谢您的帮助,我能够通过导入 JSON 并使用 data = json.dumps(data) 来使其工作
猜你喜欢
  • 2020-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-23
  • 1970-01-01
  • 2022-10-06
  • 1970-01-01
  • 2020-01-28
相关资源
最近更新 更多