-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrpc_connection.py
More file actions
50 lines (40 loc) · 1.36 KB
/
rpc_connection.py
File metadata and controls
50 lines (40 loc) · 1.36 KB
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 base64
import json
from http.client import HTTPConnection
class RPC_Connection:
def __init__(self, user, password, host="127.0.0.1", port=44555):
creds = bytes(f"{user}:{password}", "ascii")
self.auth = f"Basic {base64.b64encode(creds).decode('ascii')}"
self.conn = HTTPConnection(host, port, 30.0)
def command(self, method, params=None):
obj = {
"jsonrpc": "1.0",
"method": method,
}
if params is None:
obj["params"] = []
else:
obj["params"] = params
print("POST "+"/ " + str(json.dumps(obj)))
self.conn.request(
"POST",
"/",
json.dumps(obj),
{"Authorization": self.auth, "content-type": "application/json"},
)
resp = self.conn.getresponse()
if resp is None:
print("JSON-RPC: no response")
return None
body = resp.read()
resp_obj = json.loads(body)
if resp_obj is None:
print("JSON-RPC: cannot JSON-decode body")
return None
if "error" in resp_obj and resp_obj["error"] != None:
return resp_obj["error"]
if "result" not in resp_obj:
print("JSON-RPC: no result in object")
return None
print(resp_obj["result"])
return resp_obj["result"]