handle a jsonrpc request

        req - request as jsonrpc-dict
        validate - validate the request? (default: True)

        returns jsonrpc-dict with result or error
978952
def handle_request(self, req, validate=True):
        '''
        
        '''

        #result that will be filled and returned
        res = {'jsonrpc': '2.0', 'id': -1, 'result': None}

        logging.debug('')
        logging.debug('--------------------REQUEST' +
                      '--------------------\n' +
                      json.dumps(req,
                                 sort_keys=True,
                                 indent=4,
                                 separators=(',', ': ')))
        logging.debug('-----------------------------------------------')

        notification = False
        if self._sessionmaker:
            session = self._sessionmaker()
        try:
            #validate request
            if validate:
                self._validate_format(req)
                self._validate_params(req)

            method = req['method']

            #check if request is a notification
            try:
                getattr(self._methods[method]['fct'], '__SLOJSONRPCNotification__')
                notification = True
            except AttributeError:
                notification = False

            #call the python function
            if 'params' in req:
                fct = self._methods[method]['fct']
                if isinstance(req['params'], dict):
                    req['params']['session'] = session
                    res['result'] = fct(**req['params'])
                else:
                    res['result'] = fct(session, req['params'])
            else:
                res['result'] = self._methods[method]['fct'](session)
        except SLOJSONRPCError as e:
            res = e.to_json(req.get('id', None))
        except:
            logging.debug('Uncaught Exception:')
            logging.debug('-------------------\n' + traceback.format_exc())
            res = SLOJSONRPCError(-32603).to_json(req.get('id', None))

        session.close()

        logging.debug('--------------------RESULT' +
                      '--------------------\n' +
                      json.dumps(res,
                                 sort_keys=True,
                                 indent=4,
                                 separators=(',', ': ')))
        logging.debug('----------------------------------------------')

        #return None if a notification
        if notification:
            return None
        elif not 'error' in res:
            res['id'] = req['id']

        return res
1016432
def handle_single_request(self, request_object):
        
        if not isinstance(request_object, (MethodCall, Notification)):
            raise TypeError("Invalid type for request_object")

        method_name = request_object.method_name
        params = request_object.params
        req_id = request_object.id

        request_body = self.build_request_body(method_name, params, id=req_id)
        http_request = self.build_http_request_obj(request_body)

        try:
            response = urllib.request.urlopen(http_request)
        except urllib.request.HTTPError as e:
            raise CalledServiceError(e)

        if not req_id:
            return

        response_body = json.loads(response.read().decode())
        return response_body
141973
def _handle_request(self, request):
        """"""
        if 'types' in self.method_data[request['method']]:
            self._validate_params_types(request['method'], request['params'])

        if self.serve_exception:
            raise self.serve_exception()
        d = self._call_method(request)
        self.pending.add(d)
        if self.timeout:
            timeout_deferred = self.reactor.callLater(self.timeout, d.cancel)

            def completed(result):
                if timeout_deferred.active():
                    # cancel the timeout_deferred if it has not been fired yet
                    # this is to prevent d's deferred chain from firing twice
                    # (and raising an exception).
                    timeout_deferred.cancel()
                return result
            d.addBoth(completed)
        try:
            result = yield d
        except defer.CancelledError:
            # The request was cancelled due to a timeout or by cancelPending
            # having been called. We return a TimeoutError to the client.
            self._remove_pending(d)
            raise TimeoutError()
        except Exception as e:
            self._remove_pending(d)
            raise e
        self._remove_pending(d)
        # Do not respond to notifications.
        if request['id'] is None:
            defer.returnValue(None)

        respond = {}
        self._fill_ver(request['jsonrpc'], respond)
        respond['result'] = result
        respond['id'] = request['id']

        defer.returnValue(respond)
159495
def request(self, service, data):
        
        _res = self._request(service, data)
        res = _res.json()[0][0]
        if res["success"] == True:
            return res["result"]
        else:
            err_msg = res["errmsg"]
            raise Exception("Request not successful: '{0}'".format(err_msg))
819421
def handle_error(self, error, req, schema, error_status_code, error_headers):
        
        status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
        response = exception_response(
            status_code,
            detail=text_type(error),
            headers=error_headers,
            content_type="application/json",
        )
        body = json.dumps(error.messages)
        response.body = body.encode("utf-8") if isinstance(body, text_type) else body
        raise response
1290966
def _validate_params(self, req):
        '''
        
        '''

        #does the method exist?
        method = req['method']
        if not method in self._methods:
            raise SLOJSONRPCError(-32601)
        fct = self._methods[method]['fct']

        #'id' is only needed for none SLOJSONRPCNotification's
        try:
            getattr(fct, '__SLOJSONRPCNotification__')
            if 'id' in req:
                logging.debug('JSONRPC: Fmt Error: no id for SLOJSONRPCNotifications')
                raise SLOJSONRPCError(-32602)
        except AttributeError:
            if not 'id' in req:
                logging.debug('JSONRPC: Fmt Error: Need an id for non SLOJSONRPCNotifications')
                raise SLOJSONRPCError(-32602)

        #get arguments and defaults for the python-function representing
        # the method
        argspec = self._methods[method]['argspec']
        args, defaults = list(argspec.args), \
            list(argspec.defaults if argspec.defaults else [])

        #ignore self and session
        if 'self' in args:
            args.remove('self')
        args.remove('session')

        #create required arguments. delete the ones with defaults
        required = list(args)
        if defaults:
            for default in defaults:
                required.pop()

        #check if we need paremeters and there are none, then error
        if len(required) > 0 and 'params' not in req:
            logging.debug('JSONRPC: Parameter Error: More than zero params required')
            raise SLOJSONRPCError(-32602)

        if 'params' in req:
            #parameters must be a dict if there is more then one
            if not isinstance(req['params'], dict) and len(required) > 1:
                logging.debug('JSONRPC: Parameter Error: "params" must be a dictionary')
                raise SLOJSONRPCError(-32602)

            if isinstance(req['params'], dict):
                #check if required parameters are there
                for key in required:
                    if not key in req['params']:
                        logging.debug('JSONRPC: Parameter Error: Required key "%s" is missing' % key)
                        raise SLOJSONRPCError(-32602)

                #check if parameters are given that do not exist in the method
                for key in req['params']:
                    if not key in required:
                        logging.debug('JSONRPC: Parameter Error: Key is not allowed "%s"' % key)
                        raise SLOJSONRPCError(-32602)
1128821
def validate_api_call(schema, raw_request, raw_response):
    
    request = normalize_request(raw_request)

    with ErrorDict() as errors:
        try:
            validate_request(
                request=request,
                schema=schema,
            )
        except ValidationError as err:
            errors['request'].add_error(err.messages or getattr(err, 'detail'))
            return

        response = normalize_response(raw_response, raw_request)

        try:
            validate_response(
                response=response,
                request_method=request.method,
                schema=schema
            )
        except ValidationError as err:
            errors['response'].add_error(err.messages or getattr(err, 'detail'))
19952
def validate(self):
        
        if not self.api_token or not self.api_token_secret:
            raise ImproperlyConfigured("'api_token' and 'api_token_secret' are required for authentication.")

        if self.response_type not in ["json", "pson", "xml", "debug", None]:
            raise ImproperlyConfigured("'%s' is an invalid response_type" % self.response_type)
12971
def json_api_call(req_function):
    
    @wraps(req_function)
    def newreq(request, *args, **kwargs):
        outp = req_function(request, *args, **kwargs)
        if issubclass(outp.__class__, HttpResponse):
            return outp
        else:
            return '%s' % json.dumps(outp, cls=LazyEncoder)
    return string_to_response("application/json")(newreq)
579330
def validate(self, form_cls, obj=None):
        ''''''
        if 'application/json' not in request.headers.get('Content-Type'):
            errors = {'Content-Type': 'expecting application/json'}
            self.abort(400, errors=errors)
        form = form_cls.from_json(request.json, obj=obj, instance=obj,
                                  csrf_enabled=False)
        if not form.validate():
            self.abort(400, errors=form.errors)
        return form
387540
def process_request(self, req, resp):
        
        if not req.client_accepts_json:
            raise falcon.HTTPNotAcceptable(
                'This API only supports responses encoded as JSON.',
                href='http://docs.examples.com/api/json')
        if req.method in ('POST', 'PUT'):
            if req.content_length != 0 and \
                            'application/json' not in req.content_type and \
                            'text/plain' not in req.content_type:
                raise falcon.HTTPUnsupportedMediaType(
                    'This API only supports requests encoded as JSON.',
                    href='http://docs.examples.com/api/json')
434744
def json(self, **kwargs):
        
        try:
            return super(ScraperResponse, self).json(**kwargs)
        except ValueError as ve:
            raise ParseException(ve)
1374291
def _do_request(request):
    
    if request.request_type is RequestType.GET:
        return requests.get(request.url, headers=request.headers)
    if request.request_type is RequestType.POST:
        return requests.post(request.url, data=json.dumps(request.post_values), headers=request.headers)
    raise ValueError('Invalid request type {}'.format(request.request_type))
1130939
def handle_error(self, error, req, schema, error_status_code, error_headers):
        
        status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS
        if status_code == 422:
            reason = "Unprocessable Entity"
        else:
            reason = None
        raise HTTPError(
            status_code,
            log_message=str(error.messages),
            reason=reason,
            messages=error.messages,
            headers=error_headers,
        )
1253449
async def receive_json(self, content: typing.Dict, **kwargs):
        
        # TODO assert format, if does not match return message.
        request_id = content.pop('request_id')
        action = content.pop('action')
        await self.handle_action(action, request_id=request_id, **content)
855061
def ensure_json_content_type(req, app):
    
    res = req.get_response(app, catch_exc_info=True)
    res.content_type = 'application/json; charset=utf-8'
    return res
276036
def do_POST(self):
        '''
        
        '''
        try:
            self._parse_request()
        except Exception as ex1:
            print(traceback.format_exc())
            self.error_response(JSONRPC_PARSE_ERROR, 'exception when parsing jsonrpc request [%s]' % (ex1))
            return
        try:
            if self.req_method.startswith('_meta_'):
                self.req_method = self.req_method.replace('_meta_', '')
                instance = self.server.meta
            else:
                instance = self.server.impl
            method = getattr(instance, self.req_method)
        except AttributeError:
            self.error_response(JSONRPC_METHOD_NOT_FOUND, 'no method named "%s"' % self.req_method)
            return
        try:
            res = method(**self.req_params)
        except Exception as ex1:
            self.error_response(JSONRPC_INTERNAL_ERROR, 'exception in call "%s(%s)" -> %s' % (self.req_method, self.req_params, ex1))
            return
        if res is None:
            self.error_response(JSONRPC_NO_RESULT, JSONRPC_NO_RESULT_STR)
        else:
            self.valid_response(res)