示例#1
0
 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
示例#2
0
    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()
示例#3
0
    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()
示例#4
0
    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
示例#5
0
    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)
示例#6
0
    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
示例#7
0
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()
示例#8
0
    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)
示例#9
0
文件: silpa.py 项目: Stultus2/silpa
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')]
示例#10
0
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')]
示例#11
0
    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)
示例#12
0
    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)
示例#13
0
# -*- 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"ആന"],
示例#14
0
文件: test.py 项目: Stultus2/silpa
# -*- 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"]})
示例#15
0
 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()
示例#16
0
 def __init__(self, req):
     self.req = req
     ServiceHandler.__init__(self, None)
示例#17
0
    def __init__(self, service):
        if service == None:
            import __main__ as service

        ServiceHandler.__init__(self, service)
示例#18
0
    def __init__(self, service):
        if service == None:
            import __main__ as service

        ServiceHandler.__init__(self, service)
示例#19
0
 def __init__(self, req):
     self.req = req
     ServiceHandler.__init__(self, None)
示例#20
0
 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()
示例#21
0
文件: silpa.py 项目: Stultus2/silpa
 def __init__(self):
     self._module_manager = ModuleManager()
     self._response=None
     self._jsonrpc_handler=ServiceHandler(self) 
示例#22
0
 def __init__(self):
     self._module_manager = ModuleManager()
     self._response = None
     self._jsonrpc_handler = ServiceHandler(self)