author | Andrey Skvortsov <andrej.skvortzov@gmail.com> |
Wed, 16 Aug 2017 12:03:46 +0300 | |
changeset 1746 | 45d6f5fba016 |
parent 1742 | 92932cd370a4 |
child 1751 | c28db6f7616b |
permissions | -rw-r--r-- |
371 | 1 |
import gluon.contrib.simplejson as simplejson |
2 |
import types |
|
3 |
import sys |
|
4 |
||
1736
7e61baa047f0
clean-up: fix PEP8 E302 expected 2 blank lines, found 1
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1730
diff
changeset
|
5 |
|
371 | 6 |
class JSONRPCServiceBase: |
7 |
||
8 |
def __init__(self): |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1740
diff
changeset
|
9 |
self.methods = {} |
371 | 10 |
|
11 |
def response(self, id, result): |
|
1740
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
12 |
return simplejson.dumps({'version': '1.1', 'id': id, |
b789b695b5c6
clean-up: fix PEP8 E231 missing whitespace after ':' or ','
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1736
diff
changeset
|
13 |
'result': result, 'error': None}) |
371 | 14 |
def error(self, id, code, message): |
15 |
return simplejson.dumps({'id': id, |
|
16 |
'version': '1.1', |
|
17 |
'error': {'name': 'JSONRPCError', |
|
18 |
'code': code, |
|
19 |
'message': message |
|
20 |
} |
|
21 |
}) |
|
22 |
||
23 |
def add_method(self, name, method): |
|
24 |
self.methods[name] = method |
|
25 |
||
26 |
def process(self, data): |
|
27 |
data = simplejson.loads(data) |
|
28 |
id, method, params = data["id"], data["method"], data["params"] |
|
29 |
if method in self.methods: |
|
30 |
try: |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1740
diff
changeset
|
31 |
result = self.methods[method](*params) |
371 | 32 |
return self.response(id, result) |
33 |
except BaseException: |
|
34 |
etype, eval, etb = sys.exc_info() |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1740
diff
changeset
|
35 |
return self.error(id, 100, '%s: %s' % (etype.__name__, eval)) |
371 | 36 |
except: |
37 |
etype, eval, etb = sys.exc_info() |
|
1742
92932cd370a4
clean-up: fix PEP8 E225 missing whitespace around operator
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
1740
diff
changeset
|
38 |
return self.error(id, 100, 'Exception %s: %s' % (etype, eval)) |
371 | 39 |
else: |
40 |
return self.error(id, 100, 'method "%s" does not exist' % method) |
|
41 |
||
42 |
def listmethods(self): |
|
1730
64d8f52bc8c8
clean-up for PEP8: fix W291 trailing whitespace
Andrey Skvortsov <andrej.skvortzov@gmail.com>
parents:
728
diff
changeset
|
43 |
return self.methods.keys() |