mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 1 | |
| 2 | """ |
| 3 | Copyright (c) 2007 Jan-Klaas Kollhof |
| 4 | |
| 5 | This file is part of jsonrpc. |
| 6 | |
| 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. |
| 11 | |
| 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. |
| 16 | |
| 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 |
| 20 | """ |
| 21 | |
| 22 | import urllib2 |
| 23 | from frontend.afe.simplejson import decoder, encoder |
| 24 | json_encoder = encoder.JSONEncoder() |
| 25 | json_decoder = decoder.JSONDecoder() |
| 26 | |
| 27 | class JSONRPCException(Exception): |
| 28 | pass |
| 29 | |
| 30 | class ServiceProxy(object): |
| 31 | def __init__(self, serviceURL, serviceName=None, headers=None): |
| 32 | self.__serviceURL = serviceURL |
| 33 | self.__serviceName = serviceName |
showard | 8e855a2 | 2008-04-15 17:32:20 +0000 | [diff] [blame^] | 34 | self.__headers = headers or {} |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 35 | |
| 36 | def __getattr__(self, name): |
| 37 | if self.__serviceName != None: |
| 38 | name = "%s.%s" % (self.__serviceName, name) |
| 39 | return ServiceProxy(self.__serviceURL, name, self.__headers) |
| 40 | |
| 41 | def __call__(self, *args, **kwargs): |
| 42 | postdata = json_encoder.encode({"method": self.__serviceName, |
| 43 | 'params': args + (kwargs,), |
| 44 | 'id':'jsonrpc'}) |
| 45 | request = urllib2.Request(self.__serviceURL, data=postdata, |
| 46 | headers=self.__headers) |
| 47 | respdata = urllib2.urlopen(request).read() |
| 48 | resp = json_decoder.decode(respdata) |
| 49 | if resp['error'] != None: |
| 50 | error_message = (resp['error']['name'] + ': ' + |
showard | 8e855a2 | 2008-04-15 17:32:20 +0000 | [diff] [blame^] | 51 | resp['error']['message'] + '\n' + |
| 52 | resp['error']['traceback']) |
mbligh | e8819cd | 2008-02-15 16:48:40 +0000 | [diff] [blame] | 53 | raise JSONRPCException(error_message) |
| 54 | else: |
| 55 | return resp['result'] |