Skip to content

version for python3 #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 25 additions & 28 deletions jsonrpc.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
#!/usr/bin/env python
# -*- coding: ascii -*-
"""
JSON-RPC (remote procedure call).

Expand Down Expand Up @@ -265,7 +263,7 @@ def dictkeyclean(d):
:Raises: UnicodeEncodeError
"""
new_d = {}
for (k, v) in d.iteritems():
for (k, v) in d.items():
new_d[str(k)] = v
return new_d

Expand Down Expand Up @@ -307,7 +305,7 @@ def dumps_request( self, method, params=(), id=0 ):
:Raises: TypeError if method/params is of wrong type or
not JSON-serializable
"""
if not isinstance(method, (str, unicode)):
if not isinstance(method, str):
raise TypeError('"method" must be a string (or unicode string).')
if not isinstance(params, (tuple, list)):
raise TypeError("params must be a tuple/list.")
Expand All @@ -323,7 +321,7 @@ def dumps_notification( self, method, params=() ):
| "method", "params" and "id" are always in this order.
:Raises: see dumps_request
"""
if not isinstance(method, (str, unicode)):
if not isinstance(method, str):
raise TypeError('"method" must be a string (or unicode string).')
if not isinstance(params, (tuple, list)):
raise TypeError("params must be a tuple/list.")
Expand Down Expand Up @@ -373,11 +371,11 @@ def loads_request( self, string ):
"""
try:
data = self.loads(string)
except ValueError, err:
except ValueError as err:
raise RPCParseError("No valid JSON. (%s)" % str(err))
if not isinstance(data, dict): raise RPCInvalidRPC("No valid RPC-package.")
if "method" not in data: raise RPCInvalidRPC("""Invalid Request, "method" is missing.""")
if not isinstance(data["method"], (str, unicode)):
if not isinstance(data["method"], str):
raise RPCInvalidRPC("""Invalid Request, "method" must be a string.""")
if "id" not in data: data["id"] = None #be liberal
if "params" not in data: data["params"] = () #be liberal
Expand All @@ -401,7 +399,7 @@ def loads_response( self, string ):
"""
try:
data = self.loads(string)
except ValueError, err:
except ValueError as err:
raise RPCParseError("No valid JSON. (%s)" % str(err))
if not isinstance(data, dict): raise RPCInvalidRPC("No valid RPC-package.")
if "id" not in data: raise RPCInvalidRPC("""Invalid Response, "id" missing.""")
Expand Down Expand Up @@ -483,7 +481,7 @@ def dumps_request( self, method, params=(), id=0 ):
:Raises: TypeError if method/params is of wrong type or
not JSON-serializable
"""
if not isinstance(method, (str, unicode)):
if not isinstance(method, str):
raise TypeError('"method" must be a string (or unicode string).')
if not isinstance(params, (tuple, list, dict)):
raise TypeError("params must be a tuple/list/dict or None.")
Expand All @@ -503,7 +501,7 @@ def dumps_notification( self, method, params=() ):
| "jsonrpc", "method" and "params" are always in this order.
:Raises: see dumps_request
"""
if not isinstance(method, (str, unicode)):
if not isinstance(method, str):
raise TypeError('"method" must be a string (or unicode string).')
if not isinstance(params, (tuple, list, dict)):
raise TypeError("params must be a tuple/list/dict or None.")
Expand Down Expand Up @@ -554,15 +552,15 @@ def loads_request( self, string ):
"""
try:
data = self.loads(string)
except ValueError, err:
except ValueError as err:
raise RPCParseError("No valid JSON. (%s)" % str(err))
if not isinstance(data, dict): raise RPCInvalidRPC("No valid RPC-package.")
if "jsonrpc" not in data: raise RPCInvalidRPC("""Invalid Response, "jsonrpc" missing.""")
if not isinstance(data["jsonrpc"], (str, unicode)):
if not isinstance(data["jsonrpc"], str):
raise RPCInvalidRPC("""Invalid Response, "jsonrpc" must be a string.""")
if data["jsonrpc"] != "2.0": raise RPCInvalidRPC("""Invalid jsonrpc version.""")
if "method" not in data: raise RPCInvalidRPC("""Invalid Request, "method" is missing.""")
if not isinstance(data["method"], (str, unicode)):
if not isinstance(data["method"], str):
raise RPCInvalidRPC("""Invalid Request, "method" must be a string.""")
if "params" not in data: data["params"] = ()
#convert params-keys from unicode to str
Expand All @@ -589,12 +587,12 @@ def loads_response( self, string ):
:Raises: | RPCFault+derivates for error-packages/faults, RPCParseError, RPCInvalidRPC
"""
try:
data = self.loads(string)
except ValueError, err:
data = self.loads(string.decode("utf-8"))
except ValueError as err:
raise RPCParseError("No valid JSON. (%s)" % str(err))
if not isinstance(data, dict): raise RPCInvalidRPC("No valid RPC-package.")
if "jsonrpc" not in data: raise RPCInvalidRPC("""Invalid Response, "jsonrpc" missing.""")
if not isinstance(data["jsonrpc"], (str, unicode)):
if not isinstance(data["jsonrpc"], str):
raise RPCInvalidRPC("""Invalid Response, "jsonrpc" must be a string.""")
if data["jsonrpc"] != "2.0": raise RPCInvalidRPC("""Invalid jsonrpc version.""")
if "id" not in data: raise RPCInvalidRPC("""Invalid Response, "id" missing.""")
Expand Down Expand Up @@ -653,7 +651,7 @@ def log_dummy( message ):
pass
def log_stdout( message ):
"""print message to STDOUT"""
print message
print (message)

def log_file( filename ):
"""return a logfunc which logs to a file (in utf-8)"""
Expand Down Expand Up @@ -725,11 +723,11 @@ class TransportSTDINOUT(Transport):
"""
def send(self, string):
"""write data to STDOUT with '***SEND:' prefix """
print "***SEND:"
print string
print ("***SEND:")
print (string)
def recv(self):
"""read data from STDIN"""
print "***RECV (please enter, ^D ends.):"
print ("***RECV (please enter, ^D ends.):")
return sys.stdin.read()


Expand Down Expand Up @@ -776,7 +774,7 @@ def send( self, string ):
if self.s is None:
self.connect()
self.log( "--> "+repr(string) )
self.s.sendall( string )
self.s.sendall( str.encode(string) )
def recv( self ):
if self.s is None:
self.connect()
Expand Down Expand Up @@ -902,7 +900,7 @@ def __req( self, methodname, args=None, kwargs=None, id=0 ):
req_str = self.__data_serializer.dumps_request( methodname, kwargs, id )
try:
resp_str = self.__transport.sendrecv( req_str )
except Exception,err:
except Exception as err:
raise RPCTransportError(err)
resp = self.__data_serializer.loads_response( resp_str )
return resp[0]
Expand Down Expand Up @@ -1028,9 +1026,9 @@ def handle(self, rpcstr):
notification = True
else: #request
method, params, id = req
except RPCFault, err:
except RPCFault as err:
return self.__data_serializer.dumps_error( err, id=None )
except Exception, err:
except Exception as err:
self.log( "%d (%s): %s" % (INTERNAL_ERROR, ERROR_MESSAGE[INTERNAL_ERROR], str(err)) )
return self.__data_serializer.dumps_error( RPCFault(INTERNAL_ERROR, ERROR_MESSAGE[INTERNAL_ERROR]), id=None )

Expand All @@ -1044,11 +1042,11 @@ def handle(self, rpcstr):
result = self.funcs[method]( **params )
else:
result = self.funcs[method]( *params )
except RPCFault, err:
except RPCFault as err:
if notification:
return None
return self.__data_serializer.dumps_error( err, id=None )
except Exception, err:
except Exception as err:
if notification:
return None
self.log( "%d (%s): %s" % (INTERNAL_ERROR, ERROR_MESSAGE[INTERNAL_ERROR], str(err)) )
Expand All @@ -1058,7 +1056,7 @@ def handle(self, rpcstr):
return None
try:
return self.__data_serializer.dumps_response( result, id )
except Exception, err:
except Exception as err:
self.log( "%d (%s): %s" % (INTERNAL_ERROR, ERROR_MESSAGE[INTERNAL_ERROR], str(err)) )
return self.__data_serializer.dumps_error( RPCFault(INTERNAL_ERROR, ERROR_MESSAGE[INTERNAL_ERROR]), id )

Expand All @@ -1070,4 +1068,3 @@ def serve(self, n=None):
self.__transport.serve( self.handle, n )

#=========================================