Guest User

Untitled

a guest
May 21st, 2021
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.37 KB | None | 0 0
  1. import base64, json
  2. from http.client import HTTPConnection
  3.  
  4.  
  5. class RPC_Connection:
  6.     def __init__(self, user, password, host="127.0.0.1", port=44555):
  7.         creds = bytes(f"{user}:{password}", "ascii")
  8.         self.auth = f"Basic {base64.b64encode(creds).decode('ascii')}"
  9.         self.conn = HTTPConnection(host, port, 30.0)
  10.  
  11.     def command(self, method, params=None):
  12.         obj = {
  13.             "jsonrpc": "1.0",
  14.             "method": method,
  15.         }
  16.  
  17.         if params is None:
  18.             obj["params"] = []
  19.         else:
  20.             obj["params"] = params
  21.  
  22.         #print ("POST "+"/ "+ str(json.dumps(obj)) )
  23.         self.conn.request(
  24.             "POST",
  25.             "/",
  26.             json.dumps(obj),
  27.             {"Authorization": self.auth, "content-type": "application/json"},
  28.         )
  29.  
  30.         resp = self.conn.getresponse()
  31.         if resp is None:
  32.             print("JSON-RPC: no response")
  33.             return None
  34.  
  35.         body = resp.read()
  36.         resp_obj = json.loads(body)
  37.  
  38.         if resp_obj is None:
  39.             print("JSON-RPC: cannot JSON-decode body")
  40.             return None
  41.  
  42.         if "error" in resp_obj and resp_obj["error"] != None:
  43.             return resp_obj["error"]
  44.  
  45.         if "result" not in resp_obj:
  46.             print("JSON-RPC: no result in object")
  47.             return None
  48.  
  49.         return resp_obj["result"]
Add Comment
Please, Sign In to add comment