Produce a JSONRPC request.
438776
def jsonrpc_request(method, identifier, params=None):
    """"""
    return '{}\r\n'.format(json.dumps({
        'id': identifier,
        'method': method,
        'params': params or {},
        'jsonrpc': '2.0'
    })).encode()
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
1147706
def _encode_request(self, request):
        """"""
        obj = request_to_dict(request, self.spider)
        return self.serializer.dumps(obj)
930489
def get_json(response):
    """"""

    json_field_or_function = getattr(response, 'json', None)
    if callable(json_field_or_function):
        return response.json()
    else:
        return jsonutils.loads(response.content)
1164585
async def request(self, method, path, json=None, auth=True):
        """"""
        url = 'http://{}/api/'.format(self.host)
        if auth:
            url += '{}/'.format(self.username)
        url += path

        try:
            async with self.websession.request(method, url, json=json) as res:
                if res.content_type != 'application/json':
                    raise ResponseError(
                        'Invalid content type: {}'.format(res.content_type))
                data = await res.json()
                _raise_on_error(data)
                return data
        except client_exceptions.ClientError as err:
            raise RequestError(
                'Error requesting data from {}: {}'.format(self.host, err)
            ) from None
702353
def _fetch_remote_json(service_url, params=None, use_http_post=False):
    """"""
    if not params:
        params = {}

    request_url, response = _fetch_remote(service_url, params, use_http_post)
    if six.PY3:
        str_response = response.read().decode('utf-8')
        return (request_url, json.loads(str_response, parse_float=Decimal))
    return (request_url, json.load(response, parse_float=Decimal))
332287
def requests_post(url, data=None, json=None, **kwargs):
    """"""
    return requests_request('post', url, data=data, json=json, **kwargs)
825156
def main(
    context: click.core.Context, method: str, request_type: str, id: Any, send: str
) -> None:
    
    exit_status = 0
    # Extract the jsonrpc arguments
    positional = [a for a in context.args if "=" not in a]
    named = {a.split("=")[0]: a.split("=")[1] for a in context.args if "=" in a}
    # Create the request
    if request_type == "notify":
        req = Notification(method, *positional, **named)
    else:
        req = Request(method, *positional, request_id=id, **named)  # type: ignore
    # Sending?
    if send:
        client = HTTPClient(send)
        try:
            response = client.send(req)
        except JsonRpcClientError as e:
            click.echo(str(e), err=True)
            exit_status = 1
        else:
            click.echo(response.text)
    # Otherwise, simply output the JSON-RPC request.
    else:
        click.echo(str(req))
    sys.exit(exit_status)
828070
def make_request(endpoint, **kwargs):
        """"""
        data = kwargs.get('json', [])
        package = kwargs.get('package', None)
        method = kwargs.get('method', 'GET')

        function = getattr(requests, method.lower())

        try:
            if package:
                response = function(endpoint, data=data,
                                    files={'file': package})
            else:
                response = function(endpoint, json=data)
        except requests.exceptions.ConnectionError:
            LOG.error("Couldn't connect to NApps server %s.", endpoint)
            sys.exit(1)

        return response
1363495
def request_payload(cls, request, request_id):
        ''''''
        payload = {
            'jsonrpc': '2.0',
            'method': request.method,
        }
        # A notification?
        if request_id is not None:
            payload['id'] = request_id
        # Preserve empty dicts as missing params is read as an array
        if request.args or request.args == {}:
            payload['params'] = request.args
        return payload
437914
def as_json(context):
    """"""
    info = {
        'info': cgi.escape(pprint.pformat(context.context)),
    }
    return Response(content_type='application/json', body=json.dumps(info))
402700
def _request(self, method, url, params=None, files=None):
        """"""
        if not params:
            params = {}
        params['apiKey'] = self.api_key

        headers = {
            'User-Agent': self.user_agent,
            'Accept': 'application/json'
        }

        try:
            if self.debug:
                print(method + ' ' + url)
                print(params)

            response = requests.request(method=method, url=self.host + url, params=params, files=files, headers=headers,
                                        timeout=self.timeout, verify=self.verify_ssl, cert=self.cert)

            if self.debug:
                print(response.status_code)
                print(response.text)

            try:
                json_response = response.json()

                message = json_response['message']
                success = json_response['success']
                response_code = json_response['responseCode']
                data = json_response['object']

                return ThreadFixResponse(message=message, success=success, response_code=response_code, data=data)
            except ValueError:
                return ThreadFixResponse(message='JSON response could not be decoded.', success=False)
        except requests.exceptions.SSLError:
            return ThreadFixResponse(message='An SSL error occurred.', success=False)
        except requests.exceptions.ConnectionError:
            return ThreadFixResponse(message='A connection error occurred.', success=False)
        except requests.exceptions.Timeout:
            return ThreadFixResponse(message='The request timed out after ' + str(self.timeout) + ' seconds.',
                                     success=False)
        except requests.exceptions.RequestException:
            return ThreadFixResponse(message='There was an error while handling the request.', success=False)
294385
def jsonp(func):
    """"""
    @wraps(func)
    def decorated(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            data = str(func(*args, **kwargs).data)
            content = str(callback) + '(' + data + ')'
            mimetype = 'application/javascript'
            return current_app.response_class(content, mimetype=mimetype)
        else:
            return func(*args, **kwargs)
    return decorated
418756
def _prepare_request_json(self, kwargs):
        """"""

        # Check for python keywords in dict
        kwargs = self._check_for_python_keywords(kwargs)

        # Check for the key 'check' in kwargs
        if 'check' in kwargs:
            od = OrderedDict()
            od['check'] = kwargs['check']
            kwargs.pop('check')
            od.update(kwargs)
            return od
        return kwargs
1348298
def handle_request(cls, request, dispatcher):
        
        rs = request if isinstance(request, JSONRPC20BatchRequest) \
            else [request]
        responses = [r for r in cls._get_responses(rs, dispatcher)
                     if r is not None]

        # notifications
        if not responses:
            return

        if isinstance(request, JSONRPC20BatchRequest):
            return JSONRPC20BatchResponse(*responses)
        else:
            return responses[0]
838779
def client_get(self, url, **kwargs):
        """"""
        response = requests.get(self.make_url(url), headers=self.headers)
        if not response.ok:
            raise Exception(
                '{status}: {reason}.\nCircleCI Status NOT OK'.format(
                    status=response.status_code, reason=response.reason))
        return response.json()
389174
def _request(self, uri, params=None, postParams=None, verb='GET'):
        """"""
        return getattr(requests, verb.lower())(self.url + uri, params=params, data=postParams, stream=True)