interface.py (1636B)
1 # standard imports 2 import uuid 3 4 # local imports 5 from .base import JSONRPCBase 6 from .error import ( 7 JSONRPCErrors, 8 ) 9 10 11 class DefaultErrorParser: 12 13 def translate(self, error): 14 code = error['error']['code'] 15 message = error['error']['message'] 16 if type(code).__name__ != 'int': 17 raise ValueError('error code is not int by {} in error {}'.format(type(code), error)) 18 19 exc = None 20 try: 21 exc = JSONRPCErrors.get(code, message) 22 except KeyError: 23 return JSONRPCUndefinedError(code, message) 24 25 26 def jsonrpc_template(request_id=None): 27 if request_id == None: 28 request_id = str(uuid.uuid4()) 29 30 return { 31 'jsonrpc': JSONRPCBase.version_string, 32 'id': request_id, 33 'method': None, 34 'params': [], 35 } 36 37 38 def jsonrpc_request(method, request_id=None): 39 req = jsonrpc_template(request_id=request_id) 40 req['method'] = method 41 return req 42 43 44 def jsonrpc_result(o, ep): 45 if o.get('error') != None: 46 raise ep.translate(o) 47 return o['result'] 48 49 50 def jsonrpc_response(request_id, result): 51 return { 52 'jsonrpc': JSONRPCBase.version_string, 53 'id': request_id, 54 'result': result, 55 } 56 57 58 def jsonrpc_error(request_id, code, message=None): 59 e = JSONRPCErrors.get(code, message) 60 return { 61 'jsonrpc': JSONRPCBase.version_string, 62 'id': request_id, 63 'error': { 64 'code': code, 65 'message': str(e), 66 }, 67 } 68 69 70 def jsonrpc_is_response_to(request, response): 71 return request['id'] == response['id'] 72 73 74