371
|
1 |
import gluon.contrib.simplejson as simplejson
|
|
2 |
import types
|
|
3 |
import sys
|
|
4 |
|
|
5 |
class JSONRPCServiceBase:
|
|
6 |
|
|
7 |
def __init__(self):
|
|
8 |
self.methods={}
|
|
9 |
|
|
10 |
def response(self, id, result):
|
|
11 |
return simplejson.dumps({'version': '1.1', 'id':id,
|
|
12 |
'result':result, 'error':None})
|
|
13 |
def error(self, id, code, message):
|
|
14 |
return simplejson.dumps({'id': id,
|
|
15 |
'version': '1.1',
|
|
16 |
'error': {'name': 'JSONRPCError',
|
|
17 |
'code': code,
|
|
18 |
'message': message
|
|
19 |
}
|
|
20 |
})
|
|
21 |
|
|
22 |
def add_method(self, name, method):
|
|
23 |
self.methods[name] = method
|
|
24 |
|
|
25 |
def process(self, data):
|
|
26 |
data = simplejson.loads(data)
|
|
27 |
id, method, params = data["id"], data["method"], data["params"]
|
|
28 |
if method in self.methods:
|
|
29 |
try:
|
|
30 |
result =self.methods[method](*params)
|
|
31 |
return self.response(id, result)
|
|
32 |
except BaseException:
|
|
33 |
etype, eval, etb = sys.exc_info()
|
|
34 |
return self.error(id, 100, '%s: %s' %(etype.__name__, eval))
|
|
35 |
except:
|
|
36 |
etype, eval, etb = sys.exc_info()
|
|
37 |
return self.error(id, 100, 'Exception %s: %s' %(etype, eval))
|
|
38 |
else:
|
|
39 |
return self.error(id, 100, 'method "%s" does not exist' % method)
|
|
40 |
|
|
41 |
def listmethods(self):
|
|
42 |
return self.methods.keys()
|
|
43 |
|