Python request module for bitcoin json rpc

0 votes

This is what i am doing

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!")

I get this error:

I've been trying for hours, and I just don't know what I'm doing wrongly. It's just for planning/research (not performant) -- playing around with some code from github -- but I need to see it functional.

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!")

I get an error as follows:

Here's the whole traceback:

Expecting value: line 1 column 1 (char 0) # prints the Exception

Traceback (most recent call last): 
  File "miner_2017.py", line 411, in <module>
    solo_miner(bin2hex("------coinbase message here -----"), "-----bitcoin address here-----")
  ---
----
---
UnboundLocalError: local variable 'response' referenced before assignment  
Aug 28, 2018 in Blockchain by slayer
• 29,370 points
2,363 views

1 answer to this question.

0 votes

This should work:

#!/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_pass))
        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']
answered Aug 28, 2018 by digger
• 26,740 points

Related Questions In Blockchain

0 votes
1 answer

How to transact custom token instead of ethers using JSON rpc?

First create your custom token. Then develop ...READ MORE

answered Jul 10, 2018 in Blockchain by digger
• 26,740 points
1,072 views
0 votes
1 answer

How to add Bitcoin as currency for my website?

You cannot use BTC as the currency ...READ MORE

answered Aug 17, 2018 in Blockchain by slayer
• 29,370 points
1,056 views
0 votes
1 answer

Bitcoin: error parsing json

Make these changes in your code: json="'{" to ...READ MORE

answered Aug 22, 2018 in Blockchain by digger
• 26,740 points
1,473 views
+1 vote
3 answers

Removing double quotes from a string from JSON response in PHP

Just remove the json_encode call, and it should work: $resp ...READ MORE

answered Sep 12, 2018 in Blockchain by digger
• 26,740 points
45,219 views
0 votes
1 answer

How do I add multiple recipients for transactions via Blockchain API?

Convert the recipes into JSON objects. x = ...READ MORE

answered Jul 6, 2018 in Blockchain by Perry
• 17,100 points
886 views
+1 vote
1 answer
0 votes
1 answer

Cant locate english.txt file while intalling Python Bitcoin module

This is related to a pybitcointools bug where the ...READ MORE

answered Aug 30, 2018 in Blockchain by slayer
• 29,370 points
801 views
0 votes
1 answer

Cant install python module for python3.6 to use Jsonrpc for altcoin

Try this  VERSION=0.1 python3 setup.py install and there's also ...READ MORE

answered Sep 7, 2018 in Blockchain by digger
• 26,740 points
910 views
0 votes
1 answer

NodeJS POST Request Over JSON-RPC

You're missing the --header option: curl --request POST \ ...READ MORE

answered Sep 28, 2018 in Blockchain by digger
• 26,740 points
2,371 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP