【问题标题】:bitcoin json rpc with python requests module?带有python请求模块的比特币json rpc?
【发布时间】:2017-06-30 05:47:45
【问题描述】:

我已经尝试了几个小时,但我只是不知道我做错了什么。它只是用于计划/研究(不是高性能)——玩弄一些来自 github 的代码——但我需要看到它的功能。

RPC_USER = username
RPC_PASS = pasword
rpc_id =  ID HERE
jsonrpc = "2.0"
payload = {"jsonrpc": jsonrpc, "id": rpc_id, "method": method, "params": params}
authstr = base64.encodestring(bytes('%s:%s' % (RPC_USER, RPC_PASS), 'utf-8')).strip() 
request_headers = {"Authorization": "Basic %s" % authstr, 'content-type': 'application/json'}
try:
    response = requests.get(RPC_URL, headers = request_headers, data = json.dumps(payload)).json()
    print(response['result'])      
except Exception as e: print(str(e))
if response['id'] != rpc_id:
        raise ValueError("invalid response id!")

我收到如下错误:

这是整个追溯:

Expecting value: line 1 column 1 (char 0) # 打印异常

Traceback (most recent call last): 
  File "miner_2017.py", line 411, in <module>
    solo_miner(bin2hex("------coinbase message here -----"), "-----bitcoin address here-----")
  File "miner_2017.py", line 401, in solo_miner
    mined_block, hps = block_mine(rpc_getblocktemplate(), coinbase_message, 0, address, timeout=60)
  File "miner_2017.py", line 63, in rpc_getblocktemplate
    try: return rpc("getblocktemplate", [{}])
  File "miner_2017.py", line 52, in rpc
    if response['id'] != rpc_id:
UnboundLocalError: local variable 'response' referenced before assignment  

在做了一些查看之后,从字节对象而不是字符串对象解码 json 对象似乎是一个问题。我不知道如何解决这个问题。由于 json 问题,“响应”变量分配似乎不成功。如何从请求中获取字符串形式的 json 对象?

有人能帮帮我吗?谢谢

【问题讨论】:

  • 请显示完整的错误回溯,而不仅仅是最后一行的一部分。
  • 添加了其余的回溯。

标签: python json python-requests rpc bitcoin


【解决方案1】:
#!/usr/bin/env python

import getpass
import json
import requests    

def instruct_wallet(method, params):
    url = "http://127.0.0.1:8332/"
    payload = json.dumps({"method": method, "params": params})
    headers = {'content-type': "application/json", 'cache-control': "no-cache"}
    try:
        response = requests.request("POST", url, data=payload, headers=headers, auth=(rpc_user, rpc_password))
        return json.loads(response.text)
    except requests.exceptions.RequestException as e:
        print e
    except:
        print 'No response from Wallet, check Bitcoin is running on this machine'

rpc_user='foo'
rpc_password='bar'
passphrase = getpass.getpass('Enter your wallet passphrase: ')
timeout = raw_input('Unlock for how many seconds: ')

answer = instruct_wallet('walletpassphrase', [passphrase, timeout])
if answer['error'] != None:
    print answer['error']
else:
    print answer['result']

我正在为 Altcoins 使用类似的东西

【讨论】:

  • 这段代码变量名有误,rpc_password 用rpc_pass 引用。除此之外,这运作良好。
  • 帮我解决了解析错误{"error":{"code":-32700,"message":"Parse error."},"id":null,"jsonrpc":"2.0"} 发现我需要使用 json.dumps() 来防止双引号 " 被转换为单引号 '
【解决方案2】:
import decimal
import itertools
import json

import requests

id_counter = itertools.count()


class BTCJsonRPC(object):

    def __init__(self, url, user, passwd, log, method=None, timeout=30):
        self.url = url
        self._user = user
        self._passwd = passwd
        self._method_name = method
        self._timeout = timeout
        self._log = log

    def __getattr__(self, method_name):
        return BTCJsonRPC(self.url, self._user, self._passwd, self._log, method_name, timeout=self._timeout)

    def __call__(self, *args):
        # rpc json call
        playload = json.dumps({'jsonrpc': '2.0', 'id': next(id_counter), "method": self._method_name, "params": args})
        headers = {'Content-type': 'application/json'}
        resp = None
        try:
            resp = requests.post(self.url, headers=headers, data=playload, timeout=self._timeout,
                                 auth=(self._user, self._passwd))
            resp = resp.json(parse_float=decimal.Decimal)
        except Exception as e:
            error_msg = resp.text if resp is not None else e
            msg = u"{} {}:[{}] \n {}".format('post', self._method_name, args, error_msg)
            self._log.error(msg)
            return

        if resp.get('error') is not None:
            e = resp['error']
            self._log.error('{}:[{}]\n {}:{}'.format(self._method_name, args, e['code'], e['message']))
            return None
        elif 'result' not in resp:
            self._log.error('[{}]:[{}]\n MISSING JSON-RPC RESULT'.format(self._method_name, args, ))
            return None

        return resp['result']

【讨论】:

    【解决方案3】:

    我很确定您只需将使用 GET 更改为 POST,即:

    改变

    response = requests.get(RPC_URL, headers = request_headers, data = json.dumps(payload)).json()

    response = requests.post(RPC_URL, headers=request_headers, data=json.dumps(payload)).json()

    事实上,当我用GET 尝试这个(没有将响应转储到json)时,我得到了405 响应。在使用它进行进一步调试之前,您应该始终查看您的响应对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-27
      • 2014-11-13
      • 1970-01-01
      • 2019-04-04
      相关资源
      最近更新 更多