3 Copyright (c) 2007 Jan-Klaas Kollhof
5 This file is part of jsonrpc.
7 jsonrpc is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
12 This software is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with this software; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 from jsonrpc import loads, dumps, JSONEncodeException
25 def ServiceMethod(fn):
26 fn.IsServiceMethod = True
29 class ServiceException(Exception):
32 class ServiceRequestNotTranslatable(ServiceException):
35 class BadServiceRequest(ServiceException):
38 class ServiceMethodNotFound(ServiceException):
39 def __init__(self, name):
42 class ServiceHandler(object):
44 def __init__(self, service):
47 def handleRequest(self, json):
53 req = self.translateRequest(json)
54 except ServiceRequestNotTranslatable, e:
61 methName = req['method']
64 err = BadServiceRequest(json)
68 meth = self.findServiceEndpoint(methName)
74 result = self.invokeServiceEndpoint(meth, args)
78 resultdata = self.translateResult(result, err, id_)
82 def translateRequest(self, data):
86 raise ServiceRequestNotTranslatable(data)
89 def findServiceEndpoint(self, name):
91 meth = getattr(self.service, name)
92 if getattr(meth, "IsServiceMethod"):
95 raise ServiceMethodNotFound(name)
96 except AttributeError:
97 raise ServiceMethodNotFound(name)
99 def invokeServiceEndpoint(self, meth, args):
102 def translateResult(self, rslt, err, id_):
104 err = {"name": err.__class__.__name__, "message":err.message}
108 data = dumps({"result":rslt,"id":id_,"error":err})
109 except JSONEncodeException, e:
110 err = {"name": "JSONEncodeException", "message":"Result Object Not Serializable"}
111 data = dumps({"result":None, "id":id_,"error":err})