-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_rpc_client.py
50 lines (39 loc) · 1.25 KB
/
json_rpc_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import json
import logging
import requests
class UnauthorizedError(Exception):
pass
class JsonRpcCallError(Exception):
pass
class JsonRpcClient:
def __init__(self, endpoint, username, password):
self.endpoint = endpoint
self.username = username
self.password = password
def call(self, method, params=[]):
headers = {'content-type': 'application/json'}
payload = {
'jsonrpc': '2.0',
'id': 0,
'method': method,
'params': params,
}
logging.debug(
"calling json-rpc method '{}' with params {}".format(
method, params))
response = requests.post(
self.endpoint,
auth=(self.username, self.password),
headers=headers,
data=json.dumps(payload))
if response.status_code == 401:
logging.warn('authorization failed')
raise UnauthorizedError
try:
response = response.json()
except ValueError:
logging.error('json-rpc response did not contain valid json')
raise
if response.get('error'):
raise JsonRpcCallError(response['error']['message'])
return response['result']