コード例 #1
0
 def _marshaled_single_dispatch(self, request):
     # TODO - Use the multiprocessing and skip the response if
     # it is a notification
     # Put in support for custom dispatcher here
     # (See SimpleXMLRPCServer._marshaled_dispatch)
     method = request.get('method')
     params = request.get('params')
     try:
         response = self._dispatch(method, params)
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
     if 'id' not in request.keys() or request['id'] == None:
         # It's a notification
         return None
     try:
         response = jsonrpclib.dumps(response,
                                     methodresponse=True,
                                     rpcid=request['id'])
         return response
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
コード例 #2
0
 def _marshaled_single_dispatch(self, request):
     # TODO - Use the multiprocessing and skip the response if
     # it is a notification
     # Put in support for custom dispatcher here
     # (See SimpleXMLRPCServer._marshaled_dispatch)
     method = request.get('method')
     params = request.get('params')
     try:
         response = self._dispatch(method, params)
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
     if 'id' not in request.keys() or request['id'] == None:
         # It's a notification
         return None
     try:
         response = jsonrpclib.dumps(response,
                                     methodresponse=True,
                                     rpcid=request['id']
                                     )
         return response
     except:
         exc_type, exc_value, exc_tb = sys.exc_info()
         fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
         return fault.response()
コード例 #3
0
ファイル: methodslisting.py プロジェクト: bopo/mock-server
    def __init__(self, method, data):
        import jsonrpclib

        data = jsonrpclib.dumps(data, methodresponse=True, rpcid=1)
        method_call = '\'{"method": "%s", "id": 1}\'' % method

        super(JSONRPCMethod, self).__init__(method, data, method_call)
コード例 #4
0
    def __init__(self, method, data):
        import jsonrpclib

        data = jsonrpclib.dumps(data, methodresponse=True, rpcid=1)
        method_call = '\'{"method": "%s", "id": 1}\'' % method

        super(JSONRPCMethod, self).__init__(method, data, method_call)
コード例 #5
0
ファイル: handlers.py プロジェクト: finalbattle/torweb
 def post(self, *args, **kwargs):
     """
         JSON-RPC 2.0
         Request Object:
             {u'jsonrpc': u'2.0', u'params': [1, 2], u'id': u'3ebm619c', u'method': u'add'}
         Response Object:
             {"jsonrpc": "2.0", "result": 3, "id": "3ebm619c"}
     """
     import jsonrpclib
     try:
         json_request = jsonrpclib.loads(self.request.body)
         params = json_request.get("params", [])
         method_name = json_request.get("method", "")
     except:
         # Bad request formatting, bad.
         raise Exception('Deal with how you want.')
     if method_name in dir(RequestHandler):
         # Pre-existing, not an implemented attribute
         raise AttributeError('%s is not implemented.' % method_name)
     try:
         method = getattr(self, method_name)
     except:
         # Attribute doesn't exist
         raise AttributeError('%s is not a valid method.' % method_name)
     if not callable(method):
         # Not callable, so not a method
         raise Exception('Attribute %s is not a method.' % method_name)
     if method_name.startswith('_') or \
             ('private' in dir(method) and method.private is True):
         # No, no. That's private.
         raise Exception('Private function %s called.' % method_name)
     response = method(*params)
     response_json = jsonrpclib.dumps(response, methodresponse=True, rpcid=json_request["id"])
     self.set_header("Content-Type", "text/json")
     self.write(response_json)
コード例 #6
0
 def serialize(self):
     if self.uri[-1] != "/":
         self.uri += "/"
         self.path += "/"
     data = jsonrpclib.dumps(self.params, self.method).encode("utf8")
     self.headers["Content-Type"] = "application/json-rpc; charset=utf-8"
     cl = len(data)
     self.headers["Content-Length"] = cl
     self.set_content_length(cl)
     return data
コード例 #7
0
    def do_GET(self):
        """
        self.send_response(501)
        response = 'Not Implemented (%s): %s' %  (self.path, self.rpc_paths)
        self.send_header("Content-type", "text/plain")
        self.send_header("Content-length", str(len(response)))
        self.end_headers()
        self.wfile.write(response)
        """
        pq = self.path.split('?', 1)
        if pq[0] and pq[0][-1] == '/':
            pq[0] = pq[0][:-1]
        path = pq[0].split('/')
        method = path.pop(-1)
        path = '/'.join(path)
        if self.rpc_paths:
            if not (path in self.rpc_paths):
                self.report_404()
                return
        #print "1111", path, method
        try:
            params = []
            kwargs = {}
            if len(pq) > 1:
                for kv in pq.pop(1).split('&'):
                    kv = kv.split('=', 1)
                    if len(kv) > 1:
                        kwargs[urllib.unquote(kv[0]).strip()] = urllib.unquote(
                            kv[1]).strip()
                    else:
                        params.append(urllib.unquote(kv[0]).strip())

            data = jsonrpclib.dumps(params,
                                    kwargs,
                                    method,
                                    methodresponse=None,
                                    encoding=None,
                                    allow_none=1)
            #print self.server
            #print data
            response = self.server._marshaled_dispatch(
                data, getattr(self, '_dispatch', None), path)
        except Exception, e:  # This should only happen if the module is buggy
            # internal error, report as HTTP server error
            self.send_response(500)

            # Send information about the exception if requested
            if hasattr(self.server, '_send_traceback_header') and \
                    self.server._send_traceback_header:
                self.send_header("X-exception", str(e))
                self.send_header("X-traceback", traceback.format_exc())

            self.send_header("Cache-control", "no-cache")
            self.send_header("Content-length", "0")
            self.end_headers()
コード例 #8
0
    def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
        """Dispatches an JSON-RPC method from marshalled (JSON) data.

        JSON-RPC methods are dispatched from the marshalled (JSON) data
        using the _dispatch method and the result is returned as
        marshalled data. For backwards compatibility, a dispatch
        function can be provided as an argument (see comment in
        SimpleJSONRPCRequestHandler.do_POST) but overriding the
        existing method through subclassing is the preferred means
        of changing method dispatch behavior.
        """

        try:
            params, kwargs, method = jsonrpclib.loads(data)
            #print "method:", method

            # generate response
            if dispatch_method is not None:
                response = dispatch_method(method, params, kwargs)
            else:
                response = self._dispatch(method, params, kwargs)
            #print 333, response
            #sys.stdout.flush()
            if isinstance(response, self._type_function):
                return response
            # wrap response in a singleton tuple
            response = (response, )
            response = jsonrpclib.dumps(response,
                                        None,
                                        methodresponse=1,
                                        allow_none=self.allow_none,
                                        encoding=self.encoding)
        except Fault, fault:
            response = jsonrpclib.dumps(fault,
                                        None,
                                        allow_none=self.allow_none,
                                        encoding=self.encoding)
コード例 #9
0
def XBMCfunction(func, params=[]):
    jsondata = jsonrpclib.dumps(params, func)
    #print jsondata

    base64string = base64.encodestring('%s:%s' % ('xbmc', 'xbmc'))[:-1]
    authheader =  "Basic %s" % base64string
    
    req = urllib2.Request("http://192.168.0.10:8080/jsonrpc", jsondata)
    req.add_header("Authorization", authheader)
    req.add_header('Content-Type', 'application/json')
    handle = urllib2.urlopen(req, timeout=1)
    html = handle.read()
    #print html
    result = json.loads(html)
    return result['result']
コード例 #10
0
 def _marshaled_dispatch(self, data, dispatch_method=None, path=None):
     #print 2222, self.dispatchers
     try:
         response = self.dispatchers[path]._marshaled_dispatch(
             data, dispatch_method, path)
     except:
         # report low level exception back to server
         # (each dispatcher should have handled their own
         # exceptions)
         exc_type, exc_value = sys.exc_info()[:2]
         response = jsonrpclib.dumps(jsonrpclib.Fault(
             1, "%s:%s" % (exc_type, exc_value)),
                                     None,
                                     encoding=self.encoding,
                                     allow_none=self.allow_none)
     return response
コード例 #11
0
 def post(self, *args, **kwargs):
     """
         JSON-RPC 2.0
         Request Object:
             {u'jsonrpc': u'2.0', u'params': [1, 2], u'id': u'3ebm619c', u'method': u'add'}
         Response Object:
             {"jsonrpc": "2.0", "result": 3, "id": "3ebm619c"}
     """
     import jsonrpclib
     try:
         json_request = jsonrpclib.loads(self.request.body)
         params = json_request.get("params", [])
         method_name = json_request.get("method", "")
     except:
         # Bad request formatting, bad.
         raise Exception('Deal with how you want.')
     if method_name in dir(RequestHandler):
         # Pre-existing, not an implemented attribute
         raise AttributeError('%s is not implemented.' % method_name)
     try:
         method = getattr(self, method_name)
     except:
         # Attribute doesn't exist
         raise AttributeError('%s is not a valid method.' % method_name)
     if not callable(method):
         # Not callable, so not a method
         raise Exception('Attribute %s is not a method.' % method_name)
     if method_name.startswith('_') or \
             ('private' in dir(method) and method.private is True):
         # No, no. That's private.
         raise Exception('Private function %s called.' % method_name)
     response = method(*params)
     response_json = jsonrpclib.dumps(response,
                                      methodresponse=True,
                                      rpcid=json_request["id"])
     self.set_header("Content-Type", "text/json")
     self.write(response_json)
コード例 #12
0
 def _dump(self, data, rpcid=1):
     return jsonrpclib.dumps(data, methodresponse=True, rpcid=rpcid)
コード例 #13
0
ファイル: jsonrpc.py プロジェクト: BlinkTunnel/stomach-server
 def _dump(self, data, rpcid=1):
     return jsonrpclib.dumps(data, methodresponse=True, rpcid=rpcid)
コード例 #14
0
        method = request.get('method')
        params = request.get('params')
        try:
            response = self._dispatch(method, params)
        except Fault, fault:
            return fault.response()
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
            return fault.response()
        if 'id' not in request.keys() or request['id'] == None:
            # It's a notification
            return None
        try:
            response = jsonrpclib.dumps(response,
                                        methodresponse=True,
                                        rpcid=request['id']
                                        )
            return response
        except:
            exc_type, exc_value, exc_tb = sys.exc_info()
            fault = Fault(-32603, '%s:%s' % (exc_type, exc_value))
            return fault.response()

    def _dispatch(self, method, params):
        func = None
        try:
            func = self.funcs[method]
        except KeyError:
            if self.instance is not None:
                if hasattr(self.instance, '_dispatch'):
                    return self.instance._dispatch(method, params)
コード例 #15
0
    def handle_request(self, environ, start_response, request_text=None):
        """Handle a single JSON-RPC request passed through a CGI post method.

        If no JSON data is given then it is read from stdin. The resulting
        JSON-RPC response is printed to stdout along with the correct HTTP
        headers.
        """

        #print 111, environ
        #sys.stdout.flush()

        if request_text is None and environ.get('REQUEST_METHOD',
                                                None) == 'GET':
            """Handle a single HTTP GET request.

            Default implementation indicates an error because
            JSON-RPC uses the POST method.
            """

            pq = environ.get("REQUEST_URI", '').split('?', 1)
            if pq[0] and pq[0][-1] == '/':
                pq[0] = pq[0][:-1]
            method = pq[0].split('/')[-1]
            params = []
            kwargs = {}
            if len(pq) > 1:
                for kv in pq.pop(1).split('&'):
                    kv = kv.split('=', 1)
                    if len(kv) > 1:
                        kwargs[urllib.unquote(kv[0]).strip()] = urllib.unquote(
                            kv[1]).strip()
                    else:
                        params.append(urllib.unquote(kv[0]).strip())
            length = -1
            request_text = jsonrpclib.dumps(params,
                                            kwargs,
                                            method,
                                            methodresponse=None,
                                            encoding=None,
                                            allow_none=1)
            """Handle a single JSON-RPC request"""

            response = jsonrpclib.gzip_encode(
                self._marshaled_dispatch(request_text))
            start_response("200 OK", [
                ("Content-Type", "application/json; charset=UTF-8"),
                ("Cache-Control", "no-cache"),
                ("Content-Encoding", "gzip"),
                ("Content-Length", str(len(response))),
            ])
            """
            code = 501
            #code = 400
            message, explain = BaseHTTPServer.BaseHTTPRequestHandler.responses[code]
            response = BaseHTTPServer.DEFAULT_ERROR_MESSAGE % {
                'code': code,
                'message': message,
                'explain': explain,
            }
            start_response("%d %s" % (code, message), [
                ("Content-Type", BaseHTTPServer.DEFAULT_ERROR_CONTENT_TYPE),
                ("Content-Length", str(len(response))),
            ])
            """
        else:
            # POST data is normally available through stdin
            try:
                length = int(environ.get("CONTENT_LENGTH", None))
            except (TypeError, ValueError):
                length = -1
            if request_text is None:
                request_text = environ["wsgi.input"].read(length)
                if "gzip" == environ.get("HTTP_CONTENT_ENCODING",
                                         environ.get("CONTENT_ENCODING")):
                    request_text = jsonrpclib.gzip_decode(request_text)
            """Handle a single JSON-RPC request"""

            response = jsonrpclib.gzip_encode(
                self._marshaled_dispatch(request_text))
            start_response("200 OK", [
                ("Content-Type", "application/json"),
                ("Content-Encoding", "gzip"),
                ("Content-Length", str(len(response))),
            ])
        return [
            response,
        ]
コード例 #16
0
            response = jsonrpclib.dumps(fault,
                                        None,
                                        allow_none=self.allow_none,
                                        encoding=self.encoding)
        except:
            # report exception back to server
            exc_type, exc_value, exc_tb = sys.exc_info()
            if hasattr(
                    self,
                    '_send_traceback_header') and self._send_traceback_header:
                exc_value = str(exc_value) + '\n' + traceback.format_exc()
                print exc_value
                sys.stdout.flush()
            response = jsonrpclib.dumps(
                jsonrpclib.Fault(1, "%s:%s" % (exc_type, exc_value)),
                None,
                encoding=self.encoding,
                allow_none=self.allow_none,
            )
        return response

    def system_listMethods(self):
        """system.listMethods() => ['add', 'subtract', 'multiple']

        Returns a list of the methods supported by the server."""

        methods = self.funcs.keys()
        if self.instance is not None:
            # Instance can implement _listMethod to return a list of
            # methods
            if hasattr(self.instance, '_listMethods'):
                methods = remove_duplicates(methods +