mirror of
https://github.com/aljazceru/python-teos.git
synced 2025-12-18 14:44:21 +01:00
Reformats code to match code guidelines
This commit is contained in:
@@ -57,9 +57,9 @@ log = logging.getLogger("BitcoinRPC")
|
||||
class JSONRPCException(Exception):
|
||||
def __init__(self, rpc_error, http_status=None):
|
||||
try:
|
||||
errmsg = '%(message)s (%(code)i)' % rpc_error
|
||||
errmsg = "%(message)s (%(code)i)" % rpc_error
|
||||
except (KeyError, TypeError):
|
||||
errmsg = ''
|
||||
errmsg = ""
|
||||
super().__init__(errmsg)
|
||||
self.error = rpc_error
|
||||
self.http_status = http_status
|
||||
@@ -71,7 +71,7 @@ def EncodeDecimal(o):
|
||||
raise TypeError(repr(o) + " is not JSON serializable")
|
||||
|
||||
|
||||
class AuthServiceProxy():
|
||||
class AuthServiceProxy:
|
||||
__id_count = 0
|
||||
|
||||
# ensure_ascii: escape unicode as \uXXXX, passed to json.dumps
|
||||
@@ -80,15 +80,15 @@ class AuthServiceProxy():
|
||||
self._service_name = service_name
|
||||
self.ensure_ascii = ensure_ascii # can be toggled on the fly by tests
|
||||
self.__url = urllib.parse.urlparse(service_url)
|
||||
user = None if self.__url.username is None else self.__url.username.encode('utf8')
|
||||
passwd = None if self.__url.password is None else self.__url.password.encode('utf8')
|
||||
authpair = user + b':' + passwd
|
||||
self.__auth_header = b'Basic ' + base64.b64encode(authpair)
|
||||
user = None if self.__url.username is None else self.__url.username.encode("utf8")
|
||||
passwd = None if self.__url.password is None else self.__url.password.encode("utf8")
|
||||
authpair = user + b":" + passwd
|
||||
self.__auth_header = b"Basic " + base64.b64encode(authpair)
|
||||
self.timeout = timeout
|
||||
self._set_conn(connection)
|
||||
|
||||
def __getattr__(self, name):
|
||||
if name.startswith('__') and name.endswith('__'):
|
||||
if name.startswith("__") and name.endswith("__"):
|
||||
# Python internal stuff
|
||||
raise AttributeError
|
||||
if self._service_name is not None:
|
||||
@@ -96,15 +96,17 @@ class AuthServiceProxy():
|
||||
return AuthServiceProxy(self.__service_url, name, connection=self.__conn)
|
||||
|
||||
def _request(self, method, path, postdata):
|
||||
'''
|
||||
"""
|
||||
Do a HTTP request, with retry if we get disconnected (e.g. due to a timeout).
|
||||
This is a workaround for https://bugs.python.org/issue3566 which is fixed in Python 3.5.
|
||||
'''
|
||||
headers = {'Host': self.__url.hostname,
|
||||
'User-Agent': USER_AGENT,
|
||||
'Authorization': self.__auth_header,
|
||||
'Content-type': 'application/json'}
|
||||
if os.name == 'nt':
|
||||
"""
|
||||
headers = {
|
||||
"Host": self.__url.hostname,
|
||||
"User-Agent": USER_AGENT,
|
||||
"Authorization": self.__auth_header,
|
||||
"Content-type": "application/json",
|
||||
}
|
||||
if os.name == "nt":
|
||||
# Windows somehow does not like to re-use connections
|
||||
# TODO: Find out why the connection would disconnect occasionally and make it reusable on Windows
|
||||
self._set_conn()
|
||||
@@ -128,39 +130,40 @@ class AuthServiceProxy():
|
||||
def get_request(self, *args, **argsn):
|
||||
AuthServiceProxy.__id_count += 1
|
||||
|
||||
log.debug("-{}-> {} {}".format(
|
||||
AuthServiceProxy.__id_count,
|
||||
self._service_name,
|
||||
json.dumps(args or argsn, default=EncodeDecimal, ensure_ascii=self.ensure_ascii),
|
||||
))
|
||||
log.debug(
|
||||
"-{}-> {} {}".format(
|
||||
AuthServiceProxy.__id_count,
|
||||
self._service_name,
|
||||
json.dumps(args or argsn, default=EncodeDecimal, ensure_ascii=self.ensure_ascii),
|
||||
)
|
||||
)
|
||||
if args and argsn:
|
||||
raise ValueError('Cannot handle both named and positional arguments')
|
||||
return {'version': '1.1',
|
||||
'method': self._service_name,
|
||||
'params': args or argsn,
|
||||
'id': AuthServiceProxy.__id_count}
|
||||
raise ValueError("Cannot handle both named and positional arguments")
|
||||
return {
|
||||
"version": "1.1",
|
||||
"method": self._service_name,
|
||||
"params": args or argsn,
|
||||
"id": AuthServiceProxy.__id_count,
|
||||
}
|
||||
|
||||
def __call__(self, *args, **argsn):
|
||||
postdata = json.dumps(self.get_request(*args, **argsn), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
|
||||
response, status = self._request('POST', self.__url.path, postdata.encode('utf-8'))
|
||||
if response['error'] is not None:
|
||||
raise JSONRPCException(response['error'], status)
|
||||
elif 'result' not in response:
|
||||
raise JSONRPCException({
|
||||
'code': -343, 'message': 'missing JSON-RPC result'}, status)
|
||||
response, status = self._request("POST", self.__url.path, postdata.encode("utf-8"))
|
||||
if response["error"] is not None:
|
||||
raise JSONRPCException(response["error"], status)
|
||||
elif "result" not in response:
|
||||
raise JSONRPCException({"code": -343, "message": "missing JSON-RPC result"}, status)
|
||||
elif status != HTTPStatus.OK:
|
||||
raise JSONRPCException({
|
||||
'code': -342, 'message': 'non-200 HTTP status code but no JSON-RPC error'}, status)
|
||||
raise JSONRPCException({"code": -342, "message": "non-200 HTTP status code but no JSON-RPC error"}, status)
|
||||
else:
|
||||
return response['result']
|
||||
return response["result"]
|
||||
|
||||
def batch(self, rpc_call_list):
|
||||
postdata = json.dumps(list(rpc_call_list), default=EncodeDecimal, ensure_ascii=self.ensure_ascii)
|
||||
log.debug("--> " + postdata)
|
||||
response, status = self._request('POST', self.__url.path, postdata.encode('utf-8'))
|
||||
response, status = self._request("POST", self.__url.path, postdata.encode("utf-8"))
|
||||
if status != HTTPStatus.OK:
|
||||
raise JSONRPCException({
|
||||
'code': -342, 'message': 'non-200 HTTP status code but no JSON-RPC error'}, status)
|
||||
raise JSONRPCException({"code": -342, "message": "non-200 HTTP status code but no JSON-RPC error"}, status)
|
||||
return response
|
||||
|
||||
def _get_response(self):
|
||||
@@ -168,44 +171,55 @@ class AuthServiceProxy():
|
||||
try:
|
||||
http_response = self.__conn.getresponse()
|
||||
except socket.timeout:
|
||||
raise JSONRPCException({
|
||||
'code': -344,
|
||||
'message': '%r RPC took longer than %f seconds. Consider '
|
||||
'using larger timeout for calls that take '
|
||||
'longer to return.' % (self._service_name,
|
||||
self.__conn.timeout)})
|
||||
if http_response is None:
|
||||
raise JSONRPCException({
|
||||
'code': -342, 'message': 'missing HTTP response from server'})
|
||||
|
||||
content_type = http_response.getheader('Content-Type')
|
||||
if content_type != 'application/json':
|
||||
raise JSONRPCException(
|
||||
{'code': -342, 'message': 'non-JSON HTTP response with \'%i %s\' from server' % (
|
||||
http_response.status, http_response.reason)},
|
||||
http_response.status)
|
||||
{
|
||||
"code": -344,
|
||||
"message": "%r RPC took longer than %f seconds. Consider "
|
||||
"using larger timeout for calls that take "
|
||||
"longer to return." % (self._service_name, self.__conn.timeout),
|
||||
}
|
||||
)
|
||||
if http_response is None:
|
||||
raise JSONRPCException({"code": -342, "message": "missing HTTP response from server"})
|
||||
|
||||
responsedata = http_response.read().decode('utf8')
|
||||
content_type = http_response.getheader("Content-Type")
|
||||
if content_type != "application/json":
|
||||
raise JSONRPCException(
|
||||
{
|
||||
"code": -342,
|
||||
"message": "non-JSON HTTP response with '%i %s' from server"
|
||||
% (http_response.status, http_response.reason),
|
||||
},
|
||||
http_response.status,
|
||||
)
|
||||
|
||||
responsedata = http_response.read().decode("utf8")
|
||||
response = json.loads(responsedata, parse_float=decimal.Decimal)
|
||||
elapsed = time.time() - req_start_time
|
||||
if "error" in response and response["error"] is None:
|
||||
log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed,
|
||||
json.dumps(response["result"], default=EncodeDecimal,
|
||||
ensure_ascii=self.ensure_ascii)))
|
||||
log.debug(
|
||||
"<-%s- [%.6f] %s"
|
||||
% (
|
||||
response["id"],
|
||||
elapsed,
|
||||
json.dumps(response["result"], default=EncodeDecimal, ensure_ascii=self.ensure_ascii),
|
||||
)
|
||||
)
|
||||
else:
|
||||
log.debug("<-- [%.6f] %s" % (elapsed, responsedata))
|
||||
return response, http_response.status
|
||||
|
||||
def __truediv__(self, relative_uri):
|
||||
return AuthServiceProxy("{}/{}".format(self.__service_url, relative_uri), self._service_name,
|
||||
connection=self.__conn)
|
||||
return AuthServiceProxy(
|
||||
"{}/{}".format(self.__service_url, relative_uri), self._service_name, connection=self.__conn
|
||||
)
|
||||
|
||||
def _set_conn(self, connection=None):
|
||||
port = 80 if self.__url.port is None else self.__url.port
|
||||
if connection:
|
||||
self.__conn = connection
|
||||
self.timeout = connection.timeout
|
||||
elif self.__url.scheme == 'https':
|
||||
elif self.__url.scheme == "https":
|
||||
self.__conn = http.client.HTTPSConnection(self.__url.hostname, port, timeout=self.timeout)
|
||||
else:
|
||||
self.__conn = http.client.HTTPConnection(self.__url.hostname, port, timeout=self.timeout)
|
||||
|
||||
@@ -7,6 +7,7 @@ from pisa.conf import FEED_PROTOCOL, FEED_ADDR, FEED_PORT
|
||||
# ToDo: #7-add-async-back-to-zmq
|
||||
class ZMQHandler:
|
||||
""" Adapted from https://github.com/bitcoin/bitcoin/blob/master/contrib/zmq/zmq_sub.py"""
|
||||
|
||||
def __init__(self, parent):
|
||||
self.zmqContext = zmq.Context()
|
||||
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
|
||||
@@ -27,7 +28,7 @@ class ZMQHandler:
|
||||
body = msg[1]
|
||||
|
||||
if topic == b"hashblock":
|
||||
block_hash = binascii.hexlify(body).decode('UTF-8')
|
||||
block_hash = binascii.hexlify(body).decode("UTF-8")
|
||||
block_queue.put(block_hash)
|
||||
|
||||
self.logger.info("New block received via ZMQ", block_hash=block_hash)
|
||||
|
||||
Reference in New Issue
Block a user