def __init__(self, name, env, id=None, version=None, summary=None, help=None, json=niceJSON(True), sysServices=True): ServiceHandler.__init__(self, name, id, version, summary, help, json, sysServices) self.env = env
def handleRequest(self, fin=None, fout=None, env=None): if fin==None: fin = sys.stdin if fout==None: fout = sys.stdout if env == None: env = os.environ try: contLen=int(env['CONTENT_LENGTH']) data = fin.read(contLen) except Exception: data = "" resultData = ServiceHandler.handleRequest(self, data) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(resultData) response += resultData #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. if sys.platform == "win32": try: import msvcrt msvcrt.setmode(fout.fileno(), os.O_BINARY) except: pass #put out the response fout.write(response) fout.flush()
def handleRequest(self, fin=None, fout=None, env=None): if fin == None: fin = sys.stdin if fout == None: fout = sys.stdout if env == None: env = os.environ try: contLen = int(env['CONTENT_LENGTH']) data = fin.read(contLen) except Exception as e: data = "" resultData = ServiceHandler.handleRequest(self, data) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(resultData) response += resultData #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. if sys.platform == "win32": try: import msvcrt msvcrt.setmode(fout.fileno(), os.O_BINARY) except: pass #put out the response fout.write(response) fout.flush()
def listMethods(self): """Overrides ServiceHandler.listMethods to add methods supplied by plugins.""" methods = ServiceHandler.listMethods(self) for plugin in self.service_plugins.extensions(self.env): methods.extend(ServiceHolder(plugin).listMethods()) return methods
def methodHelp(self, name): """Overrides ServiceHandler.methodHelp to return help on methods supplied by plugins.""" for plugin in self.service_plugins.extensions(self.env): sh = ServiceHolder(plugin) if name.startswith(sh.name) and name[len(sh.name)] == '.': return sh.methodHelp(name[len(sh.name) + 1:]) return ServiceHandler.methodHelp(self, name)
def describe(self): """Overrides ServiceHandler.describe to return help on methods supplied by plugins.""" obj = ServiceHandler.describe(self) procs = obj.setdefault('procs', []) for plugin in self.service_plugins.extensions(self.env): sh = ServiceHolder(plugin) procs.extend(sh.methodDescriptions()) return obj
class CGIServiceHandler(ServiceHandler): def __init__(self, service): if service == None: import __main__ as service ServiceHandler.__init__(self, service) def handleRequest(self, fin=None, fout=None, env=None): if fin == None: fin = sys.stdin if fout == None: fout = sys.stdout if env == None: env = os.environ try: if os.environ['REQUEST_METHOD'] == 'GET': qs = urllparse.parse_qs(os.environ['QUERY_STRING']) method = qs['method'][0] params = json.loads( urllib.unquote_plus(base64.decodestring(qs['params'][0]))) rid = qs['id'][0] data = json.dumps({ 'params': params, 'method': method, 'id': rid }) else: contLen = int(env['CONTENT_LENGTH']) data = fin.read(contLen) except Exception, e: data = "" resultData = ServiceHandler.handleRequest(self, data) response = "Content-Type: text/plain\n" response += "Content-Length: %d\n\n" % len(resultData) response += resultData #on windows all \n are converted to \r\n if stdout is a terminal and is not set to binary mode :( #this will then cause an incorrect Content-length. #I have only experienced this problem with apache on Win so far. if sys.platform == "win32": try: import msvcrt msvcrt.setmode(fout.fileno(), os.O_BINARY) except: pass #put out the response fout.write(response) fout.flush()
def findServiceEndpoint(self, name): """Overrides ServiceHandler.findServiceEndpoint to first check plugins. If a plugin is not found that matches the service endpoint then the base method is called. """ for plugin in self.service_plugins.extensions(self.env): sh = ServiceHolder(plugin) if name.startswith(sh.name) and name[len(sh.name)] == '.': return sh return ServiceHandler.findServiceEndpoint(self, name)
class Silpa(): def __init__(self): self._module_manager = ModuleManager() self._response=None self._jsonrpc_handler=ServiceHandler(self) def serve(self,environ, start_response): """ The method to serve all the requests. """ request = SilpaRequest(environ) request_uri = environ.get('PATH_INFO', '').lstrip('/') #JSON RPC requests if request_uri == "JSONRPC": data = request.get_body() start_response('200 OK', [('Content-Type', 'application/json')]) jsonreponse = self._jsonrpc_handler.handleRequest(data) return [jsonreponse.encode('utf-8')] #Check if the action is defined. if self._module_manager.find_module(request_uri ): module_instance = self._module_manager.get_module_instance(request_uri ) if(module_instance): module_instance.set_request(request) module_instance.set_start_response(start_response) #if this is a json request if request.get('json'): jsonreponse = module_instance.get_json_result() start_response('200 OK', [('Content-Type', 'application/json')]) return [jsonreponse.encode('utf-8')] response = module_instance.get_response() start_response(response.response_code, response.header) return [str(response.content).encode('utf-8')] response=SilpaResponse() if(request_uri == "index.html" or request_uri == ""): start_response('200 OK', [('Content-Type', 'text/html')]) response.content.content = get_index_page() else: response.content.content ='Requested URL not found.' start_response('404 Not found', [('Content-Type', 'text/html')]) return [str(response.content).encode('utf-8')]
class Silpa(): def __init__(self): self._module_manager = ModuleManager() self._response = None self._jsonrpc_handler = ServiceHandler(self) def serve(self, environ, start_response): """ The method to serve all the requests. """ request = SilpaRequest(environ) request_uri = environ.get('PATH_INFO', '').lstrip('/') #JSON RPC requests if request_uri == "JSONRPC": data = request.get_body() start_response('200 OK', [('Content-Type', 'application/json')]) jsonreponse = self._jsonrpc_handler.handleRequest(data) return [jsonreponse.encode('utf-8')] #Check if the action is defined. if self._module_manager.find_module(request_uri): module_instance = self._module_manager.get_module_instance( request_uri) if (module_instance): module_instance.set_request(request) module_instance.set_start_response(start_response) #if this is a json request if request.get('json'): jsonreponse = module_instance.get_json_result() start_response('200 OK', [('Content-Type', 'application/json')]) return [jsonreponse.encode('utf-8')] response = module_instance.get_response() start_response(response.response_code, response.header) return [str(response.content).encode('utf-8')] response = SilpaResponse() if (request_uri == "index.html" or request_uri == ""): start_response('200 OK', [('Content-Type', 'text/html')]) response.content.content = get_index_page() else: response.content.content = 'Requested URL not found.' start_response('404 Not found', [('Content-Type', 'text/html')]) return [str(response.content).encode('utf-8')]
def findServiceEndpoint(self, name): req = self.req (modulePath, fileName) = os.path.split(req.filename) (moduleName, ext) = os.path.splitext(fileName) if not os.path.exists(os.path.join(modulePath, moduleName + ".py")): raise ServiceImplementaionNotFound() else: if not modulePath in sys.path: sys.path.insert(0, modulePath) from mod_python import apache module = apache.import_module(moduleName, log=1) if hasattr(module, "service"): self.service = module.service elif hasattr(module, "Service"): self.service = module.Service() else: self.service = module return ServiceHandler.findServiceEndpoint(self, name)
# -*- coding: utf-8 -*- import sys sys.path.append("../") from common import * from jsonrpc import ServiceProxy from jsonrpc import JSONRPCException from jsonrpc import ServiceHandler import jsonrpc handler = ServiceHandler("") print "ready" mm = ModuleManager() print mm.getModuleInstance("TTS") print handler.listMethods() json = jsonrpc.dumps({ "method": "system.listMethods", "params": [''], 'id': '' }) print handler.handleRequest(json) json = jsonrpc.dumps({ "method": "modules.TTS.text_to_wave", "params": ["hello"], 'id': '' }) print handler.handleRequest(json) json = jsonrpc.dumps({ "method": "modules.Fortune.fortune_ml", "params": [u"ആന"],
# -*- coding: utf-8 -*- import sys sys.path.append("../") from common import * from jsonrpc import ServiceProxy from jsonrpc import JSONRPCException from jsonrpc import ServiceHandler import jsonrpc handler=ServiceHandler("") print "ready" mm = ModuleManager() print mm.getModuleInstance("TTS") print handler.listMethods() json=jsonrpc.dumps({"method":"system.listMethods", "params":[''], 'id':''}) print handler.handleRequest(json) json=jsonrpc.dumps({"method":"modules.TTS.text_to_wave", "params":["hello"], 'id':''}) print handler.handleRequest(json) json=jsonrpc.dumps({"method":"modules.Fortune.fortune_ml", "params":[u"ആന"], 'id':''}) print handler.handleRequest(json) json=jsonrpc.dumps({"method":"modules.Hyphenator.hyphenate", "params":[u"ആനയാരാമോന്"], 'id':''}) print handler.handleRequest(json) json=jsonrpc.dumps({"method":"modules.Hyphenator.hyphenate", "params":[u"hithukollaalo"], 'id':''}) print handler.handleRequest(json) json=jsonrpc.dumps({"method":"modules.LangGuess.guessLanguage", "params":[u"ആന"], 'id':''}) print handler.handleRequest(json) json=jsonrpc.dumps({"version":"1.1","method":"modules.Fortune.fortune_ml","id":2,"params":[""]}) print handler.handleRequest(json) json=jsonrpc.dumps({"version":"1.1","method":"modules.Dictionary.getdef","id":2,"params":["word","freedict-eng-hin"]}) print handler.handleRequest(json) json=jsonrpc.dumps({"version":"1.1","method":"modules.CharDetails.getdetails","id":2,"params":[u"c"]})
def handleRequest(self, data): self.req.content_type = "text/plain" data = self.req.read() resultData = ServiceHandler.handleRequest(self, data) self.req.write(resultData) self.req.flush()
def __init__(self, req): self.req = req ServiceHandler.__init__(self, None)
def __init__(self, service): if service == None: import __main__ as service ServiceHandler.__init__(self, service)
def __init__(self): self._module_manager = ModuleManager() self._response=None self._jsonrpc_handler=ServiceHandler(self)
def __init__(self): self._module_manager = ModuleManager() self._response = None self._jsonrpc_handler = ServiceHandler(self)