From 2021fe4aa854a2068440f411d42684a2448371aa Mon Sep 17 00:00:00 2001 From: Jiaqiang Xu Date: Wed, 22 Aug 2018 18:24:32 +0800 Subject: [PATCH] [pysearpc] Support json return type. (#33) * [pysearpc] Support json return type. * Added tests for json return type --- pysearpc/client.py | 15 +++++++++++++++ pysearpc/test_pysearpc.py | 11 +++++++++++ 2 files changed, 26 insertions(+) diff --git a/pysearpc/client.py b/pysearpc/client.py index 741ef40..56dcf48 100644 --- a/pysearpc/client.py +++ b/pysearpc/client.py @@ -85,6 +85,19 @@ def _fret_objlist(ret_str): return l +def _fret_json(ret_str): + try: + dicts = json.loads(ret_str) + except: + raise SearpcError('Invalid response format') + + if dicts.has_key('err_code'): + raise SearpcError(dicts['err_msg']) + + if dicts['ret']: + return dicts['ret'] + else: + return None def searpc_func(ret_type, param_types): @@ -101,6 +114,8 @@ def searpc_func(ret_type, param_types): fret = _fret_int elif ret_type == "string": fret = _fret_string + elif ret_type == "json": + fret = _fret_json else: raise SearpcError('Invial return type') diff --git a/pysearpc/test_pysearpc.py b/pysearpc/test_pysearpc.py index cc1e236..a40f525 100755 --- a/pysearpc/test_pysearpc.py +++ b/pysearpc/test_pysearpc.py @@ -22,6 +22,10 @@ def init_server(): searpc_server.create_service(SVCNAME) searpc_server.register_function(SVCNAME, add, 'add') searpc_server.register_function(SVCNAME, mul, 'multi') + searpc_server.register_function(SVCNAME, json_func, 'json_func') + +def json_func(a, b): + return {'a': a, 'b': b} class DummyTransport(SearpcTransport): @@ -40,6 +44,10 @@ class RpcMixin(object): def multi(self, x, y): pass + @searpc_func("json", ["string", "int"]) + def json_func(self, x, y): + pass + class DummyRpcClient(SearpcClient, RpcMixin): def __init__(self): self.transport = DummyTransport() @@ -86,6 +94,9 @@ class SearpcTest(unittest.TestCase): v = client.multi('abc', 2) self.assertEqual(v, 'abcabc') + v = client.json_func(1, 2) + self.assertEqual(v, json_func(1, 2)) + def setup_logging(level=logging.INFO): kw = { # 'format': '[%(asctime)s][%(pathname)s]: %(message)s',