Internal helper for handling API responses from the Quoine server.
        Raises the appropriate exceptions when necessary; otherwise, returns the
        response.
972712
def _handle_response(response):
        

        if not str(response.status_code).startswith('2'):
            raise KucoinAPIException(response)
        try:
            res = response.json()

            if 'code' in res and res['code'] != "200000":
                raise KucoinAPIException(response)

            if 'success' in res and not res['success']:
                raise KucoinAPIException(response)

            # by default return full response
            # if it's a normal response we have a data attribute, return that
            if 'data' in res:
                res = res['data']
            return res
        except ValueError:
            raise KucoinRequestException('Invalid Response: %s' % response.text)
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'])
812649
def _adapt_response(self, response):
        """"""
        if 'application/json' in response.headers['content-type']:
            body = response.json()
            status = response.status_code

            if body.get('error'):
                return self._simple_response_to_error_adapter(status, body)

        raise UnknownHttpError(response)
1069181
def handleException(exception):
    
    serverException = exception
    if not isinstance(exception, exceptions.BaseServerException):
        with app.test_request_context():
            app.log_exception(exception)
        serverException = exceptions.getServerError(exception)
    error = serverException.toProtocolElement()
    # If the exception is being viewed by a web browser, we can render a nicer
    # view.
    if flask.request and 'Accept' in flask.request.headers and \
            flask.request.headers['Accept'].find('text/html') != -1:
        message = "<h1>Error {}</h1><pre>{}</pre>".format(
                    serverException.httpStatus,
                    protocol.toJson(error))
        if serverException.httpStatus == 401 \
                or serverException.httpStatus == 403:
            message += "Please try <a href=\"/login\">logging in</a>."
        return message
    else:
        responseStr = protocol.toJson(error)
        return getFlaskResponse(responseStr, serverException.httpStatus)
1374735
def _process_response(self, response, object_mapping=None):
        
        try:
            pretty_response = response.json()
        except ValueError:
            pretty_response = response
        for handler in self._response_handlers:
            if handler.applies_to(self, response):
                log.debug("{} matched: {}".format(handler.__name__, pretty_response))
                r = handler(self, object_mapping).build(response)
                self._clean_dirty_objects()
                return r
        raise ZenpyException("Could not handle response: {}".format(pretty_response))
80106
def check_server(self):
        
        msg = 'API server not found. Please check your API url configuration.'

        try:
            response = self.session.head(self.domain)
        except Exception as e:
            raise_from(errors.ServerError(msg), e)

        try:
            self._check_response(response)
        except errors.NotFound as e:
            raise raise_from(errors.ServerError(msg), e)
884840
def get_response(self, **kwargs):
        
        return Response(
            json.dumps({"error": self.message}),  # pylint: disable=exception-message-attribute
            status_code=self.status_code,
            content_type="application/json",
            charset="utf-8",
            **kwargs
        )
302626
def _handle_response(self, response):
        
        status = response.status_code
        if status == 400:
          msg = u"bad request"
          raise exceptions.BadRequest(status, msg)
        elif status == 401:
          msg = u"authorization failed user:%s" % (self.sk_user)
          raise exceptions.Unauthorized(status, msg)
        elif status == 404:
          raise exceptions.NotFound()
        elif status == 422:
          msg = u"bad request"
          raise exceptions.BadRequest(status, msg)
        elif status in range(400, 500):
          msg = u"unexpected bad request"
          raise exceptions.BadRequest(status, msg) 
        elif status in range(500, 600):
          raise exceptions.ServerError()
        return response
159651
def handle_response (response):
    
    
    response = json.loads(response.read())
    
    # Was the expression valid?
    if 'error' in response:
        raise ValueError(response['error'])
    else:
        # Some of the strings returned can be parsed to integers or floats
        try:
            return json.loads(response['result'])
        except (TypeError, json.decoder.JSONDecodeError):
            # If the result is NaN, return the actual NaN float
            if response['result'] == 'NaN':
                return float('nan')
            else:
                return response['result']
1224341
async def _get_response(self, msg):
        """"""
        try:
            protocol = await self._get_protocol()
            pr = protocol.request(msg)
            r = await pr.response
            return pr, r
        except ConstructionRenderableError as e:
            raise ClientError("There was an error with the request.", e)
        except RequestTimedOut as e:
            await self._reset_protocol(e)
            raise RequestTimeout('Request timed out.', e)
        except (OSError, socket.gaierror, Error) as e:
            # aiocoap sometimes raises an OSError/socket.gaierror too.
            # aiocoap issue #124
            await self._reset_protocol(e)
            raise ServerError("There was an error with the request.", e)
        except asyncio.CancelledError as e:
            await self._reset_protocol(e)
            raise e
149061
def _handle_response(response):
        
        if not response.ok:
            raise NeverBounceAPIError(response)
        if response.headers.get('Content-Type') == 'application/octet-stream':
            return response.iter_lines()

        try:
            resp = response.json()
        except ValueError:
             raise InvalidResponseError('Failed to handle the response content-type {}.'.format(
                 response.headers.get('Content-Type'))
             )
        if 'success' in resp and not resp['success']:
            if 'msg' in resp and resp['msg'] == 'Authentication failed':
                raise AccessTokenExpired
            else:
                raise NeverBounceAPIError(response)
        return resp
1333871
def api_request(*args, **kwargs):
        
        r = requests.request(*args, **kwargs)
        return APIResponse(r)
948820
def raise_for_response(self, responses):
        
        exception_messages = [self.client.format_exception_message(response) for response in responses]
        if len(exception_messages) == 1:
            message = exception_messages[0]
        else:
            message = "[%s]" % ", ".join(exception_messages)
        raise PostmarkerException(message)
1134678
async def _handle_telegram_response(self, response, ignore=None):
        

        if ignore is None:
            ignore = set()

        ok = response.status == 200

        try:
            data = await response.json()

            if not ok:
                desc = data['description']

                if desc in ignore:
                    return

                raise PlatformOperationError(
                    'Telegram replied with an error: {}'
                    .format(desc)
                )
        except (ValueError, TypeError, KeyError):
            raise PlatformOperationError('An unknown Telegram error occurred')

        return data
439830
def response(self, request, exception):
        
        handler = self.lookup(exception)
        response = None
        try:
            if handler:
                response = handler(request=request, exception=exception)
            if response is None:
                response = self.default(request=request, exception=exception)
        except Exception:
            self.log(format_exc())
            if self.debug:
                url = getattr(request, 'url', 'unknown')
                response_message = (
                    'Exception raised in exception handler "{}" '
                    'for uri: "{}"\n{}').format(
                        handler.__name__, url, format_exc())
                self._log.error(response_message)
                return text(response_message, 500)
            else:
                return text('An error occurred while handling an error', 500)
        return response
867664
def handle_exception(error):
    """"""
    try:
        if _get_acceptable_response_type() == JSON:
            response = jsonify(error.to_dict())
            response.status_code = error.code
            return response
        else:
            return error.abort()
    except InvalidAPIUsage:
        # In addition to the original exception, we don't support the content
        # type in the request's 'Accept' header, which is a more important
        # error, so return that instead of what was originally raised.
        response = jsonify(error.to_dict())
        response.status_code = 415
        return response
833399
def _process_response(response):
        
        if response.status_code == 404:
            raise Trovebox404Error("HTTP Error %d: %s" %
                                   (response.status_code, response.reason))
        try:
            json_response = response.json()
            code = json_response["code"]
            message = json_response["message"]
        except (ValueError, KeyError):
            # Response wasn't Trovebox JSON - check the HTTP status code
            if 200 <= response.status_code < 300:
                # Status code was valid, so just reraise the exception
                raise
            else:
                raise TroveboxError("HTTP Error %d: %s" %
                                    (response.status_code, response.reason))

        if 200 <= code < 300:
            return json_response
        elif (code == DUPLICATE_RESPONSE["code"] and
               DUPLICATE_RESPONSE["message"] in message):
            raise TroveboxDuplicateError("Code %d: %s" % (code, message))
        else:
            raise TroveboxError("Code %d: %s" % (code, message))