33import json
44
55class JsonRpcException (Exception ):
6- """Base class for exceptions in this module."""
7- pass
6+ """Base class for exceptions in this module."""
7+ pass
8+
89
9-
10+ class JsonRpcParseError (Exception ):
11+ """Raised if Parse JSON-RPC 2.0 string failed.
12+ Params:
13+ rpcError - JsonRpcError """
14+ def __init__ (self , rpcError ):
15+ Exception .__init__ (self , rpcError )
16+ self .rpcError = rpcError
17+
18+
1019def defaultJsonEncode (o ):
1120 return o .__dict__
1221
@@ -15,53 +24,56 @@ class JsonRpcMessage(object):
1524
1625 @classmethod
1726 def Request (cls , id , method , params ):
18- return JsonRpcRequestObject (id , method , params )
27+ return JsonRpcRequest (id , method , params )
1928
2029 @classmethod
2130 def Notification (cls , method , params = None ):
22- return JsonRpcNotificationObject (method , params )
31+ return JsonRpcNotification (method , params )
2332
2433 @classmethod
2534 def Success (cls , id , result ):
26- return JsonRpcSuccessObject (id , result )
35+ return JsonRpcSuccessResponse (id , result )
2736
2837 @classmethod
2938 def Error (cls , id , errorobj ):
30- return JsonRpcErrorObject (id , errorobj )
39+ return JsonRpcErrorResponse (id , errorobj )
3140
3241
3342 def AsJson (self , indent = False , escape = True ):
3443 return json .dumps (self , sort_keys = True , indent = indent ,
3544 separators = (',' , ': ' ), default = defaultJsonEncode )
3645
3746
38- class JsonRpcRequestObject (JsonRpcMessage ):
47+ class JsonRpcRequest (JsonRpcMessage ):
3948 '''JSON-RPC 2.0 Request object'''
4049 def __init__ (self , id , method , params = None ):
4150 self .id = id
4251 self .method = method
4352 self .params = params
4453
4554
46- class JsonRpcNotificationObject ( JsonRpcRequestObject ):
55+ class JsonRpcNotification ( JsonRpcRequest ):
4756 '''JSON-RPC 2.0 Notification object'''
4857 def __init__ (self , method , params = None ):
49- JsonRpcRequestObject .__init__ (self , None , method , params )
58+ JsonRpcRequest .__init__ (self , None , method , params )
5059
5160
52- class JsonRpcSuccessObject (JsonRpcMessage ):
61+ class JsonRpcSuccessResponse (JsonRpcMessage ):
5362 '''JSON-RPC 2.0 Response Object reporting request success'''
5463 def __init__ (self , id , result ):
5564 self .id = id
5665 self .result = result
5766
5867
59- class JsonRpcErrorObject (JsonRpcMessage ):
60- '''JSON-RPC 2.0 Response Object reporting request error.
61- Contains JsonRpcError object'''
62- def __init__ (self , id , errorobj ):
68+ class JsonRpcErrorResponse (JsonRpcMessage ):
69+ '''JSON-RPC 2.0 Response Object reporting request error.
70+ Params:
71+ id -- errornous request id or None,
72+ err - JsonRpcError object with an error data
73+ '''
74+ def __init__ (self , id , err ):
6375 self .id = id
64- self .error = errorobj
76+ self .error = err
6577
6678
6779class JsonRpcParsedType (object ):
@@ -74,24 +86,19 @@ class JsonRpcParsedType(object):
7486
7587
7688class JsonRpcParsed (object ):
77- '''Presents a json string parse result: parsedType and payload'''
89+ '''Presents a json string parse result: parsedType and payload.
90+ Params:
91+ parsedType -- JsonRpcParsedType,
92+ payload -- JsonRpcMessage or JsonRpcError if parse failed'''
7893 def __init__ (self , parsedType , payload ):
7994 self .parsedType = parsedType
8095 self .payload = payload
8196
8297 @classmethod
8398 def Parse (cls , jsonstr ):
8499 '''Parses json formatted string.
85- Returns JsonRpcParsed object containing Parse results.'''
86-
87- def SubCheckHeader (jsondict ):
88- '''Parses header and validate values.
89- Returns True or raises JsonRpcException in case of error'''
90- if not 'jsonrpc' in jsondict :
91- raise JsonRpcException ('Message have no "jsonrpc" field' )
92- if jsondict ['jsonrpc' ] <> '2.0' :
93- raise JsonRpcException ('"jsonrpc" field value should be 2.0' )
94- return True
100+ Raises JsonRpcParseError if Parse fails.
101+ Return a JsonRpcParsed.'''
95102
96103 def SubHasId (jsondict ):
97104 return 'id' in jsondict
@@ -106,27 +113,36 @@ def SubHasValidId(jsondict):
106113 def SubHasMethod (jsondict ):
107114 return 'method' in jsondict
108115
109- def SubIsMethodValid (jsondict ):
116+ def SubIsMethodCorrect (jsondict ):
110117 '''Checks if "method" message field has valid value.
111118 Returns boolean'''
112119 methodValid = SubHasMethod (jsondict ) and (not jsondict ['method' ] is None ) \
113120 and len (jsondict ['method' ]) > 0
114121 return methodValid
115122
123+ def SubValidateHeader (jsondict ):
124+ '''Parses header and validate values.
125+ Returns True or raises JsonRpcException in case of error'''
126+ if not 'jsonrpc' in jsondict :
127+ raise JsonRpcException ('Message have no "jsonrpc" field' )
128+ if jsondict ['jsonrpc' ] <> '2.0' :
129+ raise JsonRpcException ('"jsonrpc" field value should be 2.0' )
130+ return True
131+
116132 def SubValidateMethod (jsondict ):
117133 if not SubHasMethod (jsondict ):
118134 raise JsonRpcException ('No "method" field' )
119- if not SubIsMethodValid (jsondict ):
120- raise JsonRpcException ('Invalid "method" field value' )
135+ if not SubIsMethodCorrect (jsondict ):
136+ raise JsonRpcException ('Invalid "method" field value' )
137+ return True
121138
122139 def SubParseJsonRpcObject (jsondict ):
123140 '''Check if jsondict is valid JSON-RPC 2.0 object.
124141 Returns JsonRpcParsed object containing Parse results.'''
125142 try :
126- SubCheckHeader (jsondict )
143+ SubValidateHeader (jsondict )
127144 except JsonRpcException as e :
128- return JsonRpcParsed (JsonRpcParsedType .INVALID ,
129- JsonRpcError .InvalidRequest (str (e )))
145+ raise JsonRpcParseError (JsonRpcError .InvalidRequest (str (e )))
130146
131147 isNotification = not SubHasValidId (jsondict )
132148 if isNotification :
@@ -136,10 +152,9 @@ def SubParseJsonRpcObject(jsondict):
136152 jsondict ['params' ])
137153 return JsonRpcParsed (JsonRpcParsedType .NOTIFICATION , data )
138154 except JsonRpcException as e :
139- return JsonRpcParsed (JsonRpcParsedType .INVALID ,
140- JsonRpcError .InvalidRequest (str (e )))
155+ raise JsonRpcParseError (JsonRpcError .InvalidRequest (str (e )))
141156 #else it has Id so it may be: request, success, error message
142- isRequest = SubIsMethodValid (jsondict )
157+ isRequest = SubIsMethodCorrect (jsondict )
143158 if isRequest :
144159 data = JsonRpcMessage .Request (jsondict ['id' ], \
145160 jsondict ['method' ], jsondict ['params' ])
@@ -159,18 +174,20 @@ def SubParseJsonRpcObject(jsondict):
159174 data = JsonRpcMessage .Error (jsondict ['id' ], errorobj )
160175 return JsonRpcParsed (JsonRpcParsedType .ERROR , data )
161176 # no result, no error - id only
162- return JsonRpcParsed ( JsonRpcParsedType . INVALID ,
163- JsonRpcError .InvalidRequest ('No reqired fields' ))
177+ raise JsonRpcParseError (
178+ JsonRpcError .InvalidRequest ('No reqired fields' ))
164179 try :
165180 jsondict = json .loads (jsonstr )
166- return SubParseJsonRpcObject (jsondict )
167- except ValueError as e :
168- errorobj = JsonRpcErrorObject (None , JsonRpcError .ParseError (jsonstr ))
169- return JsonRpcParsed (JsonRpcParsedType .INVALID , errorobj )
170- '''except Exception as e:
171- errorobj = JsonRpcErrorObject(None, JsonRpcError.InternalError(str(e)))
172- return JsonRpcParsed(JsonRpcParsedType.INVALID, errorobj) '''
173-
181+ except ValueError as e :
182+ print '\r \n 1--repr(e):' + repr (e )
183+ raise JsonRpcParseError (JsonRpcError .ParseError (jsonstr ))
184+ try :
185+ parsedObjInfo = SubParseJsonRpcObject (jsondict )
186+ except JsonRpcParseError as e :
187+ raise
188+ except Exception as e :
189+ raise JsonRpcParseError (JsonRpcError .InternalError (str (e )))
190+ return parsedObjInfo
174191
175192class JsonRpcError (object ):
176193 '''Class implements JSON-RPC 2.0 Error Object'''
0 commit comments