-
-
Notifications
You must be signed in to change notification settings - Fork 100
/
manager.py
143 lines (116 loc) 路 4.67 KB
/
manager.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import json
import logging
from .utils import is_invalid_params
from .exceptions import (
JSONRPCInvalidParams,
JSONRPCInvalidRequest,
JSONRPCInvalidRequestException,
JSONRPCMethodNotFound,
JSONRPCParseError,
JSONRPCServerError,
JSONRPCDispatchException,
)
from .jsonrpc1 import JSONRPC10Response
from .jsonrpc2 import (
JSONRPC20BatchRequest,
JSONRPC20BatchResponse,
JSONRPC20Response,
)
from .jsonrpc import JSONRPCRequest
logger = logging.getLogger(__name__)
class JSONRPCResponseManager(object):
""" JSON-RPC response manager.
Method brings syntactic sugar into library. Given dispatcher it handles
request (both single and batch) and handles errors.
Request could be handled in parallel, it is server responsibility.
:param str request_str: json string. Will be converted into
JSONRPC20Request, JSONRPC20BatchRequest or JSONRPC10Request
:param dict dispatcher: dict<function_name:function>.
"""
RESPONSE_CLASS_MAP = {
"1.0": JSONRPC10Response,
"2.0": JSONRPC20Response,
}
@classmethod
def handle(cls, request_str, dispatcher, context=None):
if isinstance(request_str, bytes):
request_str = request_str.decode("utf-8")
try:
data = json.loads(request_str)
except (TypeError, ValueError):
return JSONRPC20Response(error=JSONRPCParseError()._data)
try:
request = JSONRPCRequest.from_data(data)
except JSONRPCInvalidRequestException:
return JSONRPC20Response(error=JSONRPCInvalidRequest()._data)
return cls.handle_request(request, dispatcher, context)
@classmethod
def handle_request(cls, request, dispatcher, context=None):
""" Handle request data.
At this moment request has correct jsonrpc format.
:param dict request: data parsed from request_str.
:param jsonrpc.dispatcher.Dispatcher dispatcher:
.. versionadded: 1.8.0
"""
rs = request if isinstance(request, JSONRPC20BatchRequest) \
else [request]
responses = [r for r in cls._get_responses(rs, dispatcher, context)
if r is not None]
# notifications
if not responses:
return
if isinstance(request, JSONRPC20BatchRequest):
response = JSONRPC20BatchResponse(*responses)
response.request = request
return response
else:
return responses[0]
@classmethod
def _get_responses(cls, requests, dispatcher, context=None):
""" Response to each single JSON-RPC Request.
:return iterator(JSONRPC20Response):
.. versionadded: 1.9.0
TypeError inside the function is distinguished from Invalid Params.
"""
for request in requests:
def make_response(**kwargs):
response = cls.RESPONSE_CLASS_MAP[request.JSONRPC_VERSION](
_id=request._id, **kwargs)
response.request = request
return response
output = None
try:
method = dispatcher[request.method]
except KeyError:
output = make_response(error=JSONRPCMethodNotFound()._data)
else:
try:
kwargs = request.kwargs
if context is not None:
context_arg = dispatcher.context_arg_for_method.get(
request.method)
if context_arg:
context["request"] = request
kwargs[context_arg] = context
result = method(*request.args, **kwargs)
except JSONRPCDispatchException as e:
output = make_response(error=e.error._data)
except Exception as e:
data = {
"type": e.__class__.__name__,
"args": e.args,
"message": str(e),
}
logger.exception("API Exception: {0}".format(data))
if isinstance(e, TypeError) and is_invalid_params(
method, *request.args, **request.kwargs):
output = make_response(
error=JSONRPCInvalidParams(data=data)._data)
else:
output = make_response(
error=JSONRPCServerError(data=data)._data)
else:
output = make_response(result=result)
finally:
if not request.is_notification:
yield output