'''\ A python client for jsonserver. This is a separate file that is not needed for jsonserver to work. It can be used to - test json components from the command line - create a standalone python json-rpc client. This file needs to import minjson.py, it uses nothing else from the server. ''' import urllib2 from minjson import read, write request_content_type = 'application/json-rpc' pythonkwmarker = 'pythonKwMaRkEr' class JsonRpcError(Exception): pass class JsonserverClient(object): '''A Jsonserver client. On creation it is bound to an url and you can call up methods on it. Example:: c = JsonserverClient('http://localhost:9777/xx1/edit_title_content') result = c.title_widget(widget_mode=1) ''' class Opener(object): def __init__(self, baseurl, method): self.baseurl = baseurl self.method = method def __call__(self, *args, **kw): # build the data if kw: args += ({pythonkwmarker: kw}, ) data = { 'id': 'httpReq', 'method': self.method, 'params': args, } raw_data = write(data, 'utf-8', 'utf-8') # headers={'Content-Type': request_content_type} r = urllib2.Request(self.baseurl, raw_data, headers=headers) f = urllib2.urlopen(r) # raw_response = f.read() response = read(raw_response, 'utf-8') if response['error']: raise JsonRpcError, 'Error: %s' % (response['error'], ) result = response['result'] return result def __init__(self, baseurl): '''Create a Jsonserver client class Then you can call methods on this class ''' self._baseurl = baseurl def __getattr__(self, name): # If a new method is called up, a descriptor is created for it # and it is stored in the class. if not name or name[0] == '_': raise JsonRpcError('Method names cannot start with "_". (%s)' % (name, )) method = self.Opener(self._baseurl, name) setattr(self, name, method) return method if __name__ == '__main__': c = JsonserverClient('http://localhost:9676/xx1/edit_title_content') result = c.title_widget(widget_mode=1) print result