-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.py
83 lines (66 loc) · 2.25 KB
/
rpc.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import requests
import json
from typing import List, Union, Any
class RPC:
def __init__(
self,
rpc_user: str,
rpc_password: str,
port:int = 15715 #default port is 15715
) -> None:
self.port:int = port
#boiler plate for a session
self.session = requests.Session()
self.session.auth = (rpc_user,rpc_password)
def call(
self,
method:str,
params: Union[str, int, List[Any]] = [],
silent_error:bool = False
) -> Union[dict, None]:
url:str = "http://127.0.0.1:" + str(self.port)
if isinstance(params, str) or isinstance(params, int):
params: List[Any] = [params] #wrap in list if its a string or int
if len(params) > 0:
#command with one arg
payload = json.dumps(
{
"jsonrpc":1.0,
"method": method,
"params": params,
"id":"avw-calc"
}
)
else:
#no arg command
payload = json.dumps(
{
"jsonrpc":1.0,
"method": method,
"id":"avw-calc"
}
)
headers = {
'content-type':"text/plain",
'cache-control': "no-cache"
}
try:
response = self.session.post(url, data=payload, headers=headers)
except Exception as e:
if not silent_error:
print("Error: " + str(e))
return None
if response.status_code == 401:
if not silent_error:
print("Error: unauthorized request. Check that the username and password are correct and that you allow connections from localhost")
return None
try:
result = json.loads(response.text)["result"]
except Exception as e:
if not silent_error:
print("Error: " + str(e))
print(response.text)
return None
if result == None and not silent_error:
print("Error: " + response.text)
return result