Beispiel #1
0
    def call(self, method, *args, **kwargs):
        """
        Creates the JSON-RPC request string, calls the HTTP server, converts
        JSON-RPC response string to python and returns the result.

        :param method: Name of the method which will be called on the HTTP server.
            Or a list with RPC-Request-Dictionaries. Syntax::

                "<MethodName>" or [<JsonRpcRequestDict>, ...]

            RPC-Request-Dictionaries will be made with the function
            *rpcrequest.create_request_dict()*.
        """

        # Create JSON-RPC-request
        if isinstance(method, basestring):
            request_json = rpcrequest.create_request_json(method, *args, **kwargs)
        else:
            assert not args and not kwargs
            request_json = json.dumps(method)

        # Call the HTTP-JSON-RPC server
        response_json = http_request(
            url = self.url,
            json_string = request_json,
            username = self.username,
            password = self.password,
            gzipped=self.gzip_requests,
            timeout = self.timeout,
            additional_headers = self.additional_headers,
            content_type = self.content_type,
            cookies = self.cookies

        )
        if not response_json:
            return

        # Convert JSON-RPC-response to python-object
        response = rpcresponse.parse_response_json(response_json)
        if isinstance(response, rpcresponse.Response):
            if response.error:
                # Raise error
                if response.error.code in rpcerror.jsonrpcerrors:
                    raise rpcerror.jsonrpcerrors[response.error.code](
                        message = response.error.message,
                        data = response.error.data
                    )
                else:
                    raise rpcerror.JSONApplicationError(
                        code=response.error.code,
                        message=response.error.message,
                        data=response.error.data
                    )
            else:
                # Return result
                return response.result
        elif isinstance(response, list):
            # Bei Listen wird keine Fehlerauswerung gemacht
            return response
Beispiel #2
0
def create_request_json(method, *args, **kwargs):
    """
    Returns a JSON-RPC-String for a method

    :param method: Name of the method
    :param args: Positional parameters
    :param kwargs: Named parameters
    """

    return json.dumps(create_request_dict(method, *args, **kwargs))
Beispiel #3
0
def create_request_json(method, *args, **kwargs):
    """
    Returns a JSON-RPC-String for a method

    :param method: Name of the method
    :param args: Positional parameters
    :param kwargs: Named parameters
    """

    return json.dumps(create_request_dict(method, *args, **kwargs))
Beispiel #4
0
    def do_GET(self):
        """
        Handles HTTP-GET-Request
        """

        # Parse URL query
        query = urlparse.parse_qs(urllib.splitquery(self.path)[1])

        # jsonrpc
        jsonrpc = query.get("jsonrpc")
        if jsonrpc:
            jsonrpc = jsonrpc[0]

        # id
        id = query.get("id")
        if id:
            id = id[0]

        # method
        method = query.get("method")
        if method:
            method = method[0]

        # params
        args = []
        kwargs = {}
        params = query.get("params")
        if params:
            params = json.loads(params[0])
            if isinstance(params, list):
                args = params
                kwargs = {}
            elif isinstance(params, dict):
                args = []
                kwargs = params

        # Create JSON reqeust string
        request_dict = rpcrequest.create_request_dict(method, *args, **kwargs)
        request_dict["jsonrpc"] = jsonrpc
        request_dict["id"] = id
        request_json = json.dumps(request_dict)

        # Call
        response_json = self.call(request_json)

        # Return result
        self.send_response(code = httplib.OK)
        self.set_content_type_json()
        self.set_no_cache()
        self.set_content_length(len(response_json))
        self.end_headers()
        self.wfile.write(response_json)
Beispiel #5
0
    def do_GET(self):
        """
        Handles HTTP-GET-Request
        """

        # Parse URL query
        query = urlparse.parse_qs(urllib.splitquery(self.path)[1])

        # jsonrpc
        jsonrpc = query.get("jsonrpc")
        if jsonrpc:
            jsonrpc = jsonrpc[0]

        # id
        id = query.get("id")
        if id:
            id = id[0]

        # method
        method = query.get("method")
        if method:
            method = method[0]

        # params
        args = []
        kwargs = {}
        params = query.get("params")
        if params:
            params = json.loads(params[0])
            if isinstance(params, list):
                args = params
                kwargs = {}
            elif isinstance(params, dict):
                args = []
                kwargs = params

        # Create JSON reqeust string
        request_dict = rpcrequest.create_request_dict(method, *args, **kwargs)
        request_dict["jsonrpc"] = jsonrpc
        request_dict["id"] = id
        request_json = json.dumps(request_dict)

        # Call
        response_json = self.call(request_json)

        # Return result
        self.send_response(code=httplib.OK)
        self.set_content_type_json()
        self.set_no_cache()
        self.set_content_length(len(response_json))
        self.end_headers()
        self.wfile.write(response_json)
Beispiel #6
0
    def call(self, method, *args, **kwargs):
        """
        Creates the JSON-RPC request string, calls the HTTP server, converts
        JSON-RPC response string to python and returns the result.

        :param method: Name of the method which will be called on the HTTP server.
            Or a list with RPC-Request-Dictionaries. Syntax::

                "<MethodName>" or [<JsonRpcRequestDict>, ...]

            RPC-Request-Dictionaries will be made with the function
            *rpcrequest.create_request_dict()*.
        """

        # Create JSON-RPC-request
        if isinstance(method, basestring):
            request_json = rpcrequest.create_request_json(method, *args, **kwargs)
        else:
            assert not args and not kwargs
            request_json = json.dumps(method)

        # Call the HTTP-JSON-RPC server
        response_json = http_request(
            url = self.url,
            json_string = request_json,
            username = self.username,
            password = self.password,
            timeout = self.timeout,
            additional_headers = self.additional_headers,
            content_type = self.content_type,
            cookies = self.cookies,
            gzipped = self.gzipped
        )
        if not response_json:
            return

        # Convert JSON-RPC-response to python-object
        response = rpcresponse.parse_response_json(response_json)
        if isinstance(response, rpcresponse.Response):
            if response.error:
                # Raise error
                raise rpcerror.jsonrpcerrors[response.error.code](
                    message = response.error.message,
                    data = response.error.data
                )
            else:
                # Return result
                return response.result
        elif isinstance(response, list):
            # Bei Listen wird keine Fehlerauswerung gemacht
            return response
Beispiel #7
0
def handle_cgi_request(methods = None):
    """
    Gets the JSON-RPC request from CGI environment and returns the
    result to STDOUT
    """

    import cgi
    import cgitb
    cgitb.enable()

    # get response-body
    request_json = sys.stdin.read()
    if request_json:
        # POST
        request_json = urlparse.unquote(request_json)
    else:
        # GET
        args = []
        kwargs = {}
        fields = cgi.FieldStorage()
        jsonrpc = fields.getfirst("jsonrpc")
        id = fields.getfirst("id")
        method = fields.getfirst("method")
        params = fields.getfirst("params")
        if params:
            params = json.loads(params)
            if isinstance(params, list):
                args = params
                kwargs = {}
            elif isinstance(params, dict):
                args = []
                kwargs = params

        # Create JSON request string
        request_dict = rpcrequest.create_request_dict(method, *args, **kwargs)
        request_dict["jsonrpc"] = jsonrpc
        request_dict["id"] = id
        request_json = json.dumps(request_dict)

    # Call
    response_json = rpclib.JsonRpc(methods = methods).call(request_json)

    # Return headers
    print "Content-Type: application/json"
    print "Cache-Control: no-cache"
    print "Pragma: no-cache"
    print

    # Return result
    print response_json
Beispiel #8
0
def handle_cgi_request(methods = None):
    """
    Gets the JSON-RPC request from CGI environment and returns the
    result to STDOUT
    """

    import cgi
    import cgitb
    cgitb.enable()

    # get response-body
    request_json = sys.stdin.read()
    if request_json:
        # POST
        request_json = urlparse.unquote(request_json)
    else:
        # GET
        args = []
        kwargs = {}
        fields = cgi.FieldStorage()
        jsonrpc = fields.getfirst("jsonrpc")
        id = fields.getfirst("id")
        method = fields.getfirst("method")
        params = fields.getfirst("params")
        if params:
            params = json.loads(params)
            if isinstance(params, list):
                args = params
                kwargs = {}
            elif isinstance(params, dict):
                args = []
                kwargs = params

        # Create JSON reqeust string
        request_dict = rpcrequest.create_request_dict(method, *args, **kwargs)
        request_dict["jsonrpc"] = jsonrpc
        request_dict["id"] = id
        request_json = json.dumps(request_dict)

    # Call
    response_json = rpclib.JsonRpc(methods = methods).call(request_json)

    # Return headers
    print "Content-Type: application/json"
    print "Cache-Control: no-cache"
    print "Pragma: no-cache"
    print

    # Return result
    print response_json
Beispiel #9
0
    def call(self, method, *args, **kwargs):
        """
        Creates the JSON-RPC request string, calls the HTTP server, converts
        JSON-RPC response string to python and returns the result.

        :param method: Name of the method which will be called on the HTTP server.
            Or a list with RPC-Request-Dictionaries. Syntax::

                "<MethodName>" or [<JsonRpcRequestDict>, ...]

            RPC-Request-Dictionaries will be made with the function
            *rpcrequest.create_request_dict()*.
        """

        # Create JSON-RPC-request
        if isinstance(method, basestring):
            request_json = rpcrequest.create_request_json(method, *args, **kwargs)
        else:
            request_json = json.dumps(method)
            assert not args and not kwargs

        # Call the HTTP-JSON-RPC server
        response_json = http_request(
            url = self.url,
            json_string = request_json,
            username = self.username,
            password = self.password,
            cookies = self.cookies
        )

        # Convert JSON-RPC-response to python-object
        response = rpcresponse.parse_response_json(response_json)

        if response.error:
            # Raise error
            raise rpcerror.jsonrpcerrors[response.error.code](
                message = response.error.message,
                data = response.error.data
            )
        else:
            # Return result
            return response.result
Beispiel #10
0
    def call(self, method, *args, **kwargs):
        """
        Creates the JSON-RPC request string, calls the HTTP server, converts
        JSON-RPC response string to python and returns the result.

        :param method: Name of the method which will be called on the HTTP server.
            Or a list with RPC-Request-Dictionaries. Syntax::

                "<MethodName>" or [<JsonRpcRequestDict>, ...]

            RPC-Request-Dictionaries will be made with the function
            *rpcrequest.create_request_dict()*.
        """

        # Create JSON-RPC-request
        if isinstance(method, basestring):
            request_json = rpcrequest.create_request_json(method, *args, **kwargs)
        else:
            request_json = json.dumps(method)
            assert not args and not kwargs

        # Call the HTTP-JSON-RPC server
        response_json = http_request(
            url = self.url,
            json_string = request_json,
            username = self.username,
            password = self.password
        )

        # Convert JSON-RPC-response to python-object
        response = rpcresponse.parse_response_json(response_json)

        if response.error:
            # Raise error
            raise rpcerror.jsonrpcerrors[response.error.code](
                message = response.error.message,
                data = response.error.data
            )
        else:
            # Return result
            return response.result
Beispiel #11
0
    def to_string(self):
        """
        Returns a Json-string
        """

        positional_params, named_params = self.get_splitted_params()

        # Create dictionary
        if named_params:
            params = named_params
            if positional_params:
                params["__args"] = positional_params
        else:
            params = positional_params
        data = {
            "method": self.method,
            "id": self.id,
            "jsonrpc": self.jsonrpc or "2.0",
            "params": params
        }

        # Return Json
        return json.dumps(data)
Beispiel #12
0
    def to_string(self):
        """
        Returns a Json-string
        """

        positional_params, named_params = self.get_splitted_params()

        # Create dictionary
        if named_params:
            params = named_params
            if positional_params:
                params["__args"] = positional_params
        else:
            params = positional_params
        data = {
            "method": self.method,
            "id": self.id,
            "jsonrpc": self.jsonrpc or "2.0",
            "params": params
        }

        # Return Json
        return json.dumps(data)
Beispiel #13
0
                            data = error_data or traceback_info
                        )
                    )
                )

        # Convert responses to dictionaries and filter it
        responses_ = []
        for response in responses:
            if response.id:
                responses_.append(response.to_dict())
        responses = responses_

        # Return as JSON-string (batch or normal)
        if responses:
            if len(requests) == 1:
                return json.dumps(responses[0])
            elif len(requests) > 1:
                return json.dumps(responses)


    def __call__(self, json_request):
        """
        Redirects the requests to *self.call*
        """

        return self.call(json_request)


    def __getitem__(self, key):
        """
        Gets back the requested method
Beispiel #14
0
    def to_string(self):
        """
        Returns the response as JSON-string
        """

        return json.dumps(self.to_dict())
Beispiel #15
0
    def request_handler(self, *args, **kwargs):
        """
        Json-RPC Handler
        """

        if cherrypy.request.method == "GET":
            # GET

            # jsonrpc
            jsonrpc = kwargs.get("jsonrpc")
            if jsonrpc:
                jsonrpc = jsonrpc[0]

            # id
            id = kwargs.get("id")
            if id:
                id = id[0]

            # method
            method = kwargs.get("method")
            if method:
                method = method[0]
            else:
                # Bad Request
                raise cherrypy.HTTPError(httplib.BAD_REQUEST)

            # params
            _args = []
            _kwargs = {}
            params = kwargs.get("params")
            if params:
                params = json.loads(params[0])
                if isinstance(params, list):
                    _args = params
                    _kwargs = {}
                elif isinstance(params, dict):
                    _args = []
                    _kwargs = params

            # Create JSON request string
            request_dict = rpcrequest.create_request_dict(
                method, *_args, **_kwargs)
            request_dict["jsonrpc"] = jsonrpc
            request_dict["id"] = id
            request_json = json.dumps(request_dict)
        else:
            # POST
            if "gzip" in cherrypy.request.headers.get("Content-Encoding", ""):
                request_json = decompress(cherrypy.request.body.read())
            else:
                request_json = cherrypy.request.body.read()

        # Call method
        result_string = self.call(request_json) or ""

        # Return JSON-String
        cherrypy.response.headers["Cache-Control"] = "no-cache"
        cherrypy.response.headers["Pragma"] = "no-cache"
        cherrypy.response.headers["Content-Type"] = "application/json"
        if "gzip" in cherrypy.request.headers.get("Accept-Encoding", ""):
            # Gzip-compressed
            cherrypy.response.headers["Content-Encoding"] = "gzip"
            return compress(result_string, compress_level=5)
        else:
            # uncompressed
            return result_string