Wraps and abstracts response validation and JSON parsing
        to make sure the user gets the correct response.

        :param response: The response returned to us from the request

        :returns: a dict of the json response
504000
def json_parse(self, response):
        
        try:
            data = response.json()
        except ValueError:
            data = {'meta': { 'status': 500, 'msg': 'Server Error'}, 'response': {"error": "Malformed JSON or HTML was returned."}}

        # We only really care about the response if we succeed
        # and the error if we fail
        if 200 <= data['meta']['status'] <= 399:
            return data['response']
        else:
            return data
998452
def check_response(response):
    
    if response.status_code < 200 or response.status_code > 300:
        raise ServerError('API requests returned with error: %s'
                          % response.status_code)

    try:
        response_text = loads(response.text)
    except ValueError:
        raise ServerError('The API did not returned a JSON string.')

    if not response_text:
        raise EmptyResponse()

    if 'failure' in response_text:
        if response_text['failure'] == 'Falscher Dateityp':
            raise UnsupportedFormat('Please look at picflash.org '
                                    'witch formats are supported')
        else:
            raise UnkownError(response_text['failure'])
1194389
def _check_response(self, response):
        
        if response.status_code > 299 or response.status_code < 200:
            log.debug("Received response code [%s] - headers: %s" % (response.status_code, str(response.headers)))
            try:
                _json = response.json()
                err_type = _json.get("error", '')
                if err_type == 'RecordNotFound':
                    raise RecordNotFoundException(json.dumps(_json), response=response)
                elif err_type == "TooManyValues":
                    raise TooManyValuesException(json.dumps(_json), response=response)
                else:
                    raise APIException(json.dumps(_json), response=response)
            except ValueError:
                response.raise_for_status()
701136
def _validation(response):
    
    h = hashlib.sha256(response.key_authorization.encode("utf-8"))
    return b64encode(h.digest()).decode()
963211
def _result_handler(self, response: Dict[str, Any]):
        
        res = response.get("MESSAGE")
        result = res.get("RESULT")
        return result
1036369
def _as_json(self, response):
        
        # Assume ClientResponse has "body", and otherwise it's a requests.Response
        content = response.text() if hasattr(response, "body") else response.text
        try:
            return json.loads(content)
        except ValueError:
            raise DeserializationError(
                "Error occurred in deserializing the response body.")
988518
def render_to_json_response(self, context, **response_kwargs):
        
        return HttpResponse(
            self.convert_context_to_json(context),
            content_type='application/json',
            **response_kwargs
        )
609413
def decode_response_body(response)
      check_response_status_code(response)
      body = MultiJson.load(response.body, :symbolize_keys => true)
      check_body_error(response, body)
      body
    end
85628
def render_json_response(self, context, status=200):
        
        json_context = json.dumps(context, cls=self.json_encoder_class)

        return HttpResponse(json_context,
                            content_type=self.get_content_type(),
                            status=status)
470590
def parse_response(self, response):
        
        status = response.status_code
        if response.ok:
            data = response.json()
            return HttpResponse(ok=response.ok, status=status, errors=None, data=data)
        else:
            try:
                errors = response.json()
            except ValueError:
                errors = response.content
            return HttpResponse(ok=response.ok, status=status, errors=errors, data=None)
11486
function serverResponseToRESPONSE (response) {
	try {
		const obj = JSON.parse(response);
		if (obj.result === RESPONSE_UNKNOWN) {
			return RESPONSE_UNKNOWN;
		} else {
			return obj.result.result;
		}
	} catch (e) {
		return RESPONSE_INVALID;
	}
}
665887
def handle_response(response)
      # Check our response code
      check_response_fail(response)
      return nil if blank?(response.body)

      # Return a bunch of mashes as the body if we're JSON
      begin
        response.body = JSON.parse(response.body, max_nesting: false)
        response.body = if response.body.is_a? Array
                        response.body.map { |r| Hashie::Mash.new(r) }
                      else
                        Hashie::Mash.new(response.body)
                      end
      rescue => exception
        raise "JSON parsing failed. Error details: #{exception}"
      ensure
        return response
      end
    end
1038796
def validate_response(response, validator_map):
    
    validator = validator_map.response

    # Short circuit if we are supposed to not validate anything.
    returns_nothing = validator.schema.get('type') == 'void'
    body_empty = response.body in (None, b'', b'{}', b'null')
    if returns_nothing and body_empty:
        return

    # Don't attempt to validate non-success responses in v1.2
    if not 200 <= response.status_code <= 203:
        return

    validator.validate(prepare_body(response))
228354
def process_response(self,
                         method,
                         response,
                         response_type=None,
                         objects_type=None):
        

        try:
            response_json = response.json(
                object_hook=
                lambda x: ResponseObject(x) if isinstance(x, dict) else x)
            if response_type:
                r = response_type(self, response_json.__dict__)
                response_json = r

            if 'objects' in response_json and objects_type:
                response_json.objects = [
                    objects_type(self, obj.__dict__)
                    for obj in response_json.objects
                ]
        except ValueError:
            response_json = None

        if response.status_code == 400:
            if response_json and 'error' in response_json:
                raise ValidationError(response_json.error)
            raise ValidationError(
                'A parameter is missing or is invalid while accessing resource'
                'at: {url}'.format(url=response.url))

        if response.status_code == 401:
            if response_json and 'error' in response_json:
                raise AuthenticationError(response_json.error)
            raise AuthenticationError(
                'Failed to authenticate while accessing resource at: '
                '{url}'.format(url=response.url))

        if response.status_code == 404:
            if response_json and 'error' in response_json:
                raise ResourceNotFoundError(response_json.error)
            raise ResourceNotFoundError(
                'Resource not found at: {url}'.format(url=response.url))

        if response.status_code == 405:
            if response_json and 'error' in response_json:
                raise InvalidRequestError(response_json.error)
            raise InvalidRequestError(
                'HTTP method "{method}" not allowed to access resource at: '
                '{url}'.format(method=method, url=response.url))

        if response.status_code == 500:
            if response_json and 'error' in response_json:
                raise PlivoServerError(response_json.error)
            raise PlivoServerError(
                'A server error occurred while accessing resource at: '
                '{url}'.format(url=response.url))

        if method == 'DELETE':
            if response.status_code != 204:
                raise PlivoRestError('Resource at {url} could not be '
                                     'deleted'.format(url=response.url))

        elif response.status_code not in [200, 201, 202]:
            raise PlivoRestError(
                'Received status code {status_code} for the HTTP method '
                '"{method}"'.format(
                    status_code=response.status_code, method=method))

        return response_json
420058
def check_response(self, response):
        
        if response.status_code == 401:
            raise D4S2Error(UNAUTHORIZED_MESSAGE)
        if not 200 <= response.status_code < 300:
            raise D4S2Error("Request to {} failed with {}:\n{}.".format(response.url, response.status_code,
                                                                        response.text))
43823
def _parse_response(header_data, ignore_bad_cookies=False,
                    ignore_bad_attributes=True):
    
    cookie_dicts = []
    for line in Definitions.EOL.split(header_data.strip()):
        if not line:
            break
        cookie_dict = parse_one_response(
            line, ignore_bad_cookies=ignore_bad_cookies,
            ignore_bad_attributes=ignore_bad_attributes)
        if not cookie_dict:
            continue
        cookie_dicts.append(cookie_dict)
    if not cookie_dicts:
        if not ignore_bad_cookies:
            raise InvalidCookieError(data=header_data)
        _report_invalid_cookie(header_data)
    return cookie_dicts
1174237
def _parse_response(proto, response):
        
        try:
            content = proto()
            content.ParseFromString(response.content)
            return content
        except (DecodeError, AttributeError):
            LOGGER.error('Validator response was not parsable: %s', response)
            raise errors.ValidatorResponseInvalid()