Skip to content
This repository has been archived by the owner on Dec 17, 2020. It is now read-only.

Commit

Permalink
Implemented JSON-RPC 2.0 specification. Use JSON-RPC 2.0 version as d…
Browse files Browse the repository at this point in the history
…efault.
  • Loading branch information
projekt01 committed Aug 2, 2008
1 parent d0bc50d commit c62aa22
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 33 deletions.
16 changes: 12 additions & 4 deletions CHANGES.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,21 @@
CHANGES
=======

0.5.1 (2008-01-24)
------------------
Version 0.5.2dev (unreleased)
-----------------------------

- Implemented JSON-RPC 2.0 specification. Use JSON-RPC 2.0 version as default.
Optional the version 1.0 and 1.1 can be set. See JSON-RPC 2.0 specification
for more information.


Version 0.5.1 (2008-01-24)
--------------------------

- Improved meta-data.


0.5.0 (2008-01-21)
------------------
Version 0.5.0 (2008-01-21)
--------------------------

- Initial Release
2 changes: 1 addition & 1 deletion src/z3c/json/README.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Read some data:
... u'b':['mary', 1.234]}
>>> jsonStr = jsonWriter.write(input)
>>> jsonStr
u'{"a":["fred",7],"b":["mary",1.234]}'
u'{"a": ["fred", 7], "b": ["mary", 1.234]}'


`JSONReader` Utility
Expand Down
55 changes: 41 additions & 14 deletions src/z3c/json/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,29 +34,54 @@
from z3c.json.transport import SafeTransport

logger = logging.getLogger(__name__)
JSON_RPC_VERSION = '2.0'


class _Method(object):

def __init__(self, call, name, jsonId):
def __init__(self, call, name, jsonId, jsonVersion):
self.call = call
self.name = name
self.jsonId = jsonId
self.jsonVersion = jsonVersion

def __call__(self, *args, **kwargs):
request = {}
request['version'] = '1.1'
# add our version
if self.jsonVersion == '1.0':
pass
elif self.jsonVersion == '1.1':
request['version'] = self.jsonVersion
else:
request['jsonrpc'] = self.jsonVersion
request['method'] = self.name
if len(kwargs) is not 0:
params = copy.copy(kwargs)
index = 0
for arg in args:
params[str(index)] = arg
index = index + 1
elif len(args) is not 0:
params = copy.copy(args)

if self.jsonVersion in ['1.0', '1.1']:
if len(kwargs) > 0:
params = copy.copy(kwargs)
index = 0
for arg in args:
params[str(index)] = arg
index += 1
elif len(args) > 0:
params = args
else:
params = []
else:
params = {}
# There is not support for postional and named parameters in one
# call. We propably will add support for this within a extension
# in a later version. Till then, we will raise an exception if
# we will get both paramters.
if len(args) > 0 and len(kwargs) > 0:
raise ValueError('Mixing positional and named parameters in one call is not possible')
if len(args) > 0:
params = args
elif len(kwargs) > 0:
params = kwargs
else:
params = []

# set params and write json
request['params'] = params
# add our json id
request['id'] = self.jsonId
Expand All @@ -68,14 +93,15 @@ def __call__(self, *args, **kwargs):
raise ResponseError("JSONRPC server connection error.")

def __getattr__(self, name):
return _Method(self.call, "%s.%s" % (self.name, name), self.jsonId)
return _Method(self.call, "%s.%s" % (self.name, name), self.jsonId,
self.jsonVersion)


class JSONRPCProxy(object):
"""JSON-RPC server proxy."""

def __init__(self, uri, transport=None, encoding=None,
verbose=None, jsonId=None):
verbose=None, jsonId=None, jsonVersion=JSON_RPC_VERSION):
utype, uri = urllib.splittype(uri)
if utype not in ("http", "https"):
raise IOError, "Unsupported JSONRPC protocol"
Expand All @@ -93,6 +119,7 @@ def __init__(self, uri, transport=None, encoding=None,
self.__encoding = encoding
self.__verbose = verbose
self.jsonId = jsonId or u'jsonrpc'
self.jsonVersion = jsonVersion or JSON_RPC_VERSION
self.error = None

def __request(self, request):
Expand Down Expand Up @@ -135,7 +162,7 @@ def __request(self, request):

def __getattr__(self, name):
"""This let us call methods on remote server."""
return _Method(self.__request, name, self.jsonId)
return _Method(self.__request, name, self.jsonId, self.jsonVersion)

def __repr__(self):
return ("<JSONProxy for %s%s>" % (self.__host, self.__handler))
Expand Down
18 changes: 4 additions & 14 deletions src/z3c/json/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -635,34 +635,24 @@ def tearDown(self):
tearDownServer(self)

def testSimple(self):
#from pub.dbgpclient import brk; brk('172.16.144.39')

proxy = JSONRPCProxy('http://localhost:%d/' % self.TEST_PORT)

set_next_response_json(True, "jsonrpc")

y = proxy.hello()
self.assertEqual(y, True)

x = get_last_request()
self.assertEqual(x,
"""{"version":"1.1","params":{},"method":"hello","id":"jsonrpc"}""")


"""{"params": [], "jsonrpc": "2.0", "method": "hello", "id": "jsonrpc"}""")

set_next_response_json(123, "jsonrpc")

y = proxy.greeting(u'Jessy')

self.assertEqual(y, 123)

x = get_last_request()
self.assertEqual(x,
"""{"version":"1.1","params":["Jessy"],"method":"greeting","id":"jsonrpc"}""")

"""{"params": ["Jessy"], "jsonrpc": "2.0", "method": "greeting", "id": "jsonrpc"}""")

set_next_response('blabla')

try:
y = proxy.hello()
except ResponseError:
Expand All @@ -683,14 +673,14 @@ def testSimple(self):
'call_method': 'hello',
'assert_retval': True,
'assert_request':
"""{"version":"1.1","params":{},"method":"hello","id":"jsonrpc"}""",
"""{"params": [], "jsonrpc": "2.0", "method": "hello", "id": "jsonrpc"}""",
},
{'response_json': 123,
'call_method': 'greeting',
'call_args': [u'Jessy'],
'assert_retval': 123,
'assert_request':
"""{"version":"1.1","params":["Jessy"],"method":"greeting","id":"jsonrpc"}""",
"""{"params": ["Jessy"], "jsonrpc": "2.0", "method": "greeting", "id": "jsonrpc"}""",
},
{'response': 'blabla',
'call_method': 'hello',
Expand Down

0 comments on commit c62aa22

Please sign in to comment.