Example #1
0
def _parse_result(request_body, result_body):
    """A subfunction of rpc_request, that, given the decoded JSON result,
    handles the error codes or, if everything went well, returns the result
    attribute of it. The request data has to be given too for logging and
    ID validation.

    :param request_body: The not-yet-encoded body of the request sent.
    :param result_body: The decoded body of the result received.
    """

    if request_body[u'id'] != result_body[u'id']:
        raise errors.RemoteError(
            'Request ID was not the same one as returned. %s -- %s' % (request_body[u'id'], result_body[u'id']))

    try:
        return result_body[u'result']
    except KeyError:
        _parse_error_code(request_body, result_body)
Example #2
0
def _send_request(url, data, headers, http_session=None):
    """Sends a POST request given the endpoint URL, JSON-encodable data,
    a dictionary with headers and, optionally, a session object for requests.
    """

    if http_session is None:
        http_session = requests.session()

    r = http_session.post(url, data=json.dumps(data), headers=headers)
    result = r.text
    # this will eventually raise errors, e.g. on timeout

    try:
        result_data = json.loads(result)
        log('debug', 'Valid JSON found')
    except ValueError:
        raise errors.RemoteError('Invalid JSON', result)
    else:
        return result_data