本文整理汇总了Python中jsonrpclib.Fault类的典型用法代码示例。如果您正苦于以下问题:Python Fault类的具体用法?Python Fault怎么用?Python Fault使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Fault类的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _marshaled_dispatch
def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
"""
Parses the request data (marshaled), calls method(s) and returns a
JSON string (marshaled)
:param data: A JSON request string
:param dispatch_method: Custom dispatch method (for method resolution)
:param path: Unused parameter, to keep compatibility with xmlrpclib
:return: A JSON-RPC response string (marshaled)
"""
# Parse the request
try:
request = jsonrpclib.loads(data, self.json_config)
except Exception as ex:
# Parsing/loading error
fault = Fault(-32700, 'Request {0} invalid. ({1}:{2})'
.format(data, type(ex).__name__, ex),
config=self.json_config)
_logger.warning("Error parsing request: %s", fault)
return fault.response()
# Get the response dictionary
try:
response = self._unmarshaled_dispatch(request, dispatch_method)
if response is not None:
# Compute the string representation of the dictionary/list
return jsonrpclib.jdumps(response, self.encoding)
else:
# No result (notification)
return ''
except NoMulticallResult:
# Return an empty string (jsonrpclib internal behaviour)
return ''
示例2: _marshaled_dispatch
def _marshaled_dispatch(self, data, dispatch_method=None):
"""Convert the data to a JSON RPC method request and dispatch it."""
try:
request = jsonrpclib.loads(data)
except Exception as e:
fault = Fault(-32700, "Request %s invalid. (%s)" % (data, e))
response = fault.response()
return response
if not request:
fault = Fault(-32600, "Request invalid -- no request data.")
return fault.response()
if isinstance(request, types.ListType):
# batch of requests
responses = []
for req_entry in request:
result = validate_request(req_entry)
if type(result) is Fault:
responses.append(result.response())
continue
resp_entry = self._marshaled_single_dispatch(req_entry)
if resp_entry is not None:
responses.append(resp_entry)
if len(responses) > 0:
response = "[%s]" % ",".join(responses)
else:
response = ""
else:
# single request
result = validate_request(request)
if type(result) is Fault:
return result.response()
response = self._marshaled_single_dispatch(request)
return response
示例3: _unmarshaled_dispatch
def _unmarshaled_dispatch(self, request, dispatch_method=None):
"""
Loads the request dictionary (unmarshaled), calls the method(s)
accordingly and returns a JSON-RPC dictionary (not marshaled)
:param request: JSON-RPC request dictionary (or list of)
:param dispatch_method: Custom dispatch method (for method resolution)
:return: A JSON-RPC dictionary (or an array of) or None if the request
was a notification
:raise NoMulticallResult: No result in batch
"""
if not request:
# Invalid request dictionary
fault = Fault(-32600, 'Request invalid -- no request data.',
config=self.json_config)
_logger.warning("Invalid request: %s", fault)
return fault.dump()
if isinstance(request, utils.ListType):
# This SHOULD be a batch, by spec
responses = []
for req_entry in request:
# Validate the request
result = validate_request(req_entry, self.json_config)
if isinstance(result, Fault):
responses.append(result.dump())
continue
# Call the method
resp_entry = self._marshaled_single_dispatch(req_entry,
dispatch_method)
# Store its result
if isinstance(resp_entry, Fault):
# pylint: disable=E1103
responses.append(resp_entry.dump())
elif resp_entry is not None:
responses.append(resp_entry)
if not responses:
# No non-None result
_logger.error("No result in Multicall")
raise NoMulticallResult("No result")
return responses
else:
# Single call
result = validate_request(request, self.json_config)
if isinstance(result, Fault):
return result.dump()
# Call the method
response = self._marshaled_single_dispatch(request,
dispatch_method)
if isinstance(response, Fault):
# pylint: disable=E1103
return response.dump()
return response
示例4: _marshaled_single_dispatch
def _marshaled_single_dispatch(self, request):
# TODO - Use the multiprocessing and skip the response if
# it is a notification
# Put in support for custom dispatcher here
# (See SimpleXMLRPCServer._marshaled_dispatch)
method = request.get('method')
params = request.get('params')
try:
response = self._dispatch(method, params)
except:
exc_type, exc_value, exc_tb = sys.exc_info()
fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
return fault.response()
if 'id' not in request.keys() or request['id'] == None:
# It's a notification
return None
try:
response = jsonrpclib.dumps(response,
methodresponse=True,
rpcid=request['id']
)
return response
except:
exc_type, exc_value, exc_tb = sys.exc_info()
fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
return fault.response()
示例5: _marshaled_dispatch
def _marshaled_dispatch(self, session_id, data, dispatch_method=None):
response = None
try:
request = jsonrpclib.loads(data)
except Exception, e:
fault = Fault(-32700, 'Request %s invalid. (%s)' % (data, e))
response = fault.response()
return response
示例6: _marshaled_single_dispatch
def _marshaled_single_dispatch(self, request, dispatch_method=None):
"""
Dispatches a single method call
:param request: A validated request dictionary
:param dispatch_method: Custom dispatch method (for method resolution)
:return: A JSON-RPC response dictionary, or None if it was a
notification request
"""
# TODO - Use the multiprocessing and skip the response if
# it is a notification
method = request.get('method')
params = request.get('params')
# Prepare a request-specific configuration
if 'jsonrpc' not in request and self.json_config.version >= 2:
# JSON-RPC 1.0 request on a JSON-RPC 2.0
# => compatibility needed
config = self.json_config.copy()
config.version = 1.0
else:
# Keep server configuration as is
config = self.json_config
try:
# Call the method
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params, config)
except:
# Return a fault
exc_type, exc_value, _ = sys.exc_info()
fault = Fault(-32603, '{0}:{1}'.format(exc_type, exc_value),
config=config)
return fault.dump()
if 'id' not in request or request['id'] in (None, ''):
# It's a notification, no result needed
# Do not use 'not id' as it might be the integer 0
return None
# Prepare a JSON-RPC dictionary
try:
# TODO: use a copy of the configuration, to JSON-RPC version
return jsonrpclib.dump(response, rpcid=request['id'],
is_response=True, config=config)
except:
# JSON conversion exception
exc_type, exc_value, _ = sys.exc_info()
fault = Fault(-32603, '{0}:{1}'.format(exc_type, exc_value),
config=config)
return fault.dump()
示例7: _marshaled_dispatch
def _marshaled_dispatch(self, data, client_ip=None):
response = None
try:
request = jsonrpclib.loads(data)
if not request.has_key("params"):
request["params"] = {}
request["params"]["client_ip"] = client_ip
except Exception, e:
fault = Fault(-32700, "Request %s invalid. (%s)" % (data, e))
response = fault.response()
return response
示例8: do_POST
def do_POST(self):
"""
HTTP POST method processor.
"""
if not self.is_rpc_path_valid():
logger.warning("[Response] HTTP 404 - The path requested is not " "a valid address.")
self.report_404()
return
try:
size_remaining = int(self.headers["content-length"])
L = []
while size_remaining:
chunk_size = min(size_remaining, self.MAX_CHUNK_SIZE)
L.append(self.rfile.read(chunk_size))
size_remaining -= len(L[-1])
data = "".join(L)
c_ip, c_port = self.client_address
logger.info("[Request] Client %s:%s method POST: %s" % (c_ip, c_port, data))
response = self.server._marshaled_dispatch(data)
status = 200
message = "Request accepted."
except Exception:
logger.exception("Exception processing request:")
status = 500
message = "Internal Server Error."
err_lines = traceback.format_exc().splitlines()
trace_string = "%s | %s" % (err_lines[-3], err_lines[-1])
fault = Fault(-32603, "Server error: %s" % trace_string)
response = fault.response()
finally:
logger.info("[Response] HTTP %d - %s" % (status, message))
self.send_response(status)
logger.info("[Response] Content: %s" % repr(response))
self.send_header("Content-type", "application/json-rpc")
self.send_header("Content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
self.wfile.flush()
self.connection.shutdown(1)
示例9: _marshaled_single_dispatch
def _marshaled_single_dispatch(self, request, dispatch_method=None):
"""
Dispatches a single method call
:param request: A validated request dictionary
:param dispatch_method: Custom dispatch method (for method resolution)
:return: A JSON-RPC response dictionary, or None if it was a
notification request
"""
# TODO - Use the multiprocessing and skip the response if
# it is a notification
method = request.get('method')
params = request.get('params')
try:
# Call the method
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params)
except:
# Return a fault
exc_type, exc_value, _ = sys.exc_info()
fault = Fault(-32603, '{0}:{1}'.format(exc_type, exc_value))
return fault.dump()
if 'id' not in request or request['id'] in (None, ''):
# It's a notification, no result needed
# Do not use 'not id' as it might be the integer 0
return None
# Prepare a JSON-RPC dictionary
try:
return jsonrpclib.dump(response, rpcid=request['id'],
is_response=True)
except:
# JSON conversion exception
exc_type, exc_value, _ = sys.exc_info()
fault = Fault(-32603, '{0}:{1}'.format(exc_type, exc_value))
return fault.dump()
示例10: _marshaled_dispatch
def _marshaled_dispatch(self, data, dispatch_method = None):
response = None
try:
request = jsonrpclib.loads(data)
except:
fault = Fault(-32600, 'Request %s invalid.' % data)
response = fault.response()
return response
version = get_version(request)
if not version:
fault = Fault(-32600, 'Request %s invalid.' % data)
response = fault.response()
return response
if type(request) is types.ListType:
# This SHOULD be a batch, by spec
responses = []
for req_entry in request:
resp_entry = self._marshaled_single_dispatch(req_entry)
if resp_entry is not None:
responses.append(resp_entry)
response = '[%s]' % ','.join(responses)
else:
response = self._marshaled_single_dispatch(request)
return response
示例11: _marshaled_single_dispatch
def _marshaled_single_dispatch(self, request, dispatch_method=None):
"""
Dispatches a single method call
:param request: A validated request dictionary
:param dispatch_method: Custom dispatch method (for method resolution)
:return: A JSON-RPC response dictionary, or None if it was a
notification request
"""
method = request.get('method')
params = request.get('params')
# Prepare a request-specific configuration
if 'jsonrpc' not in request and self.json_config.version >= 2:
# JSON-RPC 1.0 request on a JSON-RPC 2.0
# => compatibility needed
config = self.json_config.copy()
config.version = 1.0
else:
# Keep server configuration as is
config = self.json_config
# Test if this is a notification request
is_notification = 'id' not in request or request['id'] in (None, '')
if is_notification and self.__notification_pool is not None:
# Use the thread pool for notifications
if dispatch_method is not None:
self.__notification_pool.enqueue(dispatch_method,
method, params)
else:
self.__notification_pool.enqueue(self._dispatch,
method, params, config)
# Return immediately
return None
else:
# Synchronous call
try:
# Call the method
if dispatch_method is not None:
response = dispatch_method(method, params)
else:
response = self._dispatch(method, params, config)
except Exception as ex:
# Return a fault
fault = Fault(-32603, '{0}:{1}'.format(type(ex).__name__, ex),
config=config)
_logger.error("Error calling method %s: %s", method, fault)
return fault.dump()
if is_notification:
# It's a notification, no result needed
# Do not use 'not id' as it might be the integer 0
return None
# Prepare a JSON-RPC dictionary
try:
return jsonrpclib.dump(response, rpcid=request['id'],
is_response=True, config=config)
except Exception as ex:
# JSON conversion exception
fault = Fault(-32603, '{0}:{1}'.format(type(ex).__name__, ex),
config=config)
_logger.error("Error preparing JSON-RPC result: %s", fault)
return fault.dump()
示例12: _marshaled_single_dispatch
return response
def _marshaled_single_dispatch(self, request):
# TODO - Use the multiprocessing and skip the response if
# it is a notification
# Put in support for custom dispatcher here
# (See SimpleXMLRPCServer._marshaled_dispatch)
method = request.get('method')
params = request.get('params')
try:
response = self._dispatch(method, params)
except Fault, fault:
return fault.response()
except:
exc_type, exc_value, exc_tb = sys.exc_info()
fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
return fault.response()
if 'id' not in request.keys() or request['id'] == None:
# It's a notification
return None
try:
response = jsonrpclib.dumps(response,
methodresponse=True,
rpcid=request['id']
)
return response
except:
exc_type, exc_value, exc_tb = sys.exc_info()
fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
return fault.response()