Ejemplo n.º 1
0
    def handle_error(self, e):
        '''
        Error handler for the API transforms a raised exception into a Flask response,
        with the appropriate HTTP status code and body.

        :param Exception e: the raised Exception object

        '''
        got_request_exception.send(current_app._get_current_object(), exception=e)

        headers = Headers()
        if e.__class__ in self.error_handlers:
            handler = self.error_handlers[e.__class__]
            result = handler(e)
            default_data, code, headers = unpack(result, 500)
        elif isinstance(e, HTTPException):
            code = e.code
            default_data = {
                'message': getattr(e, 'description', HTTP_STATUS_CODES.get(code, ''))
            }
            headers = e.get_response().headers
        elif self._default_error_handler:
            result = self._default_error_handler(e)
            default_data, code, headers = unpack(result, 500)
        else:
            code = 500
            default_data = {
                'message': HTTP_STATUS_CODES.get(code, str(e)),
            }

        default_data['message'] = default_data.get('message', str(e))
        data = getattr(e, 'data', default_data)
        fallback_mediatype = None

        if code >= 500:
            exc_info = sys.exc_info()
            if exc_info[1] is None:
                exc_info = None
            current_app.log_exception(exc_info)

        elif code == 404 and current_app.config.get("ERROR_404_HELP", True):
            data['message'] = self._help_on_404(data.get('message', None))

        elif code == 406 and self.default_mediatype is None:
            # if we are handling NotAcceptable (406), make sure that
            # make_response uses a representation we support as the
            # default mediatype (so that make_response doesn't throw
            # another NotAcceptable error).
            supported_mediatypes = list(self.representations.keys())
            fallback_mediatype = supported_mediatypes[0] if supported_mediatypes else "text/plain"

        # Remove blacklisted headers
        for header in HEADERS_BLACKLIST:
            headers.pop(header, None)

        resp = self.make_response(data, code, headers, fallback_mediatype=fallback_mediatype)

        if code == 401:
            resp = self.unauthorized(resp)
        return resp
Ejemplo n.º 2
0
def get_status_msg(status_code):
    """将status code转换为status message
        200 => 'OK'
        400 => 'Bad Request'
        500 => 'Internal Server Error'
    """
    return HTTP_STATUS_CODES.get(status_code, 'Unknown Error')
Ejemplo n.º 3
0
def error_response(status_code, message=None):
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 4
0
 def as_dict(self):
     if self.args:
         message = str(self)
     else:
         message = HTTP_STATUS_CODES.get(self.status_code, '')
     return {
         'status': self.status_code,
         'message': message
     }
Ejemplo n.º 5
0
    def abort(self, status, error=None, encoder=True):
        (self.log.exception if self.app.debug and exc_info()[0] else self.log.error)(
             '%r %s %s >> %s', status, request.method, request.path,
             error or HTTP_STATUS_CODES.get(status, 'Unknown Error'))

        if error:
            return abort(status, description=error, response = self.encoders[encoder].make_response(
                dict(status=status, error=error), status=status))
        else:
            return abort(status)
Ejemplo n.º 6
0
 def error_response(status_code, description):  # pragma: no cover
     response = make_response(
         json.dumps({
             "message": HTTP_STATUS_CODES.get(status_code),
             "status": status_code,
             "description": description
         })
     )
     response.mimetype = 'application/json'
     response.status_code = status_code
     return response
Ejemplo n.º 7
0
def error_response(status_code, message=None):
    payload = {
        "error": HTTP_STATUS_CODES.get(status_code, "Unknown error"),
    }

    if message:
        payload["message"] = message

    response = jsonify(payload)
    response.status_code = status_code

    return response
def error_response(status_code, message=None):

    # Using HTTP_STATUS_CODES dictionary to get the short description of a HTTP status code.
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message

    # using jsonify method to convert the response in JSON structure.
    response = jsonify(payload)
    response.status_code = status_code

    return response
Ejemplo n.º 9
0
def response(status_code, message=None, data=None, meta=None):
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['msg'] = message
    if data:
        payload['data'] = data
    if meta:
        payload['meta'] = meta

    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 10
0
def error_response(status_code, message=None):
    """ 错误处理函数
    :param status_code:
    :param message:
    :return:
    """
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 11
0
def error_response(status_code, message=None):
    body = {
        'error': HTTP_STATUS_CODES.get(status_code),
    }

    if message:
        body['message'] = message

    response = jsonify(body)
    response.status_code = status_code

    return response
Ejemplo n.º 12
0
def error_response(status_code, message=None):
    '''
    Generates an error response payload
    jsonify() returns a default 200 for the response
    because of this, we must set the response status_code manually
    '''
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 13
0
def error_response(status_code, message=''):
    if message is None:
        response = ''
    else:
        payload = {
            'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')
        }
        if message != '':
            payload['message'] = message
        response = jsonify(payload)
        #response.status_code = status_code
    return make_response(response, status_code)
Ejemplo n.º 14
0
def error_response(status_code, message=None):
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    '''
    ###Michael: from site:  The jsonify() function returns a Flask Response object with a 
    default status code of 200, so after I create the response, I set 
    the status code to the correct one for the error.
    '''
    return response
Ejemplo n.º 15
0
def get_reason_phrase(status_code: int, default: str = 'Unknown') -> str:
    """A helper function to get the reason phrase of the given status code.

    Arguments:
        status_code: A standard HTTP status code.
        default: The default phrase to use if not found, defaults to "Unknown".

    *Version Changed: 0.6.0*

    - Add `default` parameter.
    """
    return HTTP_STATUS_CODES.get(status_code, default)
def error_response(status_code, message=None):
    """ Error handling routine which produces short descriptions
        for the provided HTTP error code.
        
        Returns: Response to client (the message and an HTTP error code)
        """
    payload = {'ERROR': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 17
0
def error_response(status_code, message=None):
    payload = {
        'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error'),
        'error_code': status_code
    }

    if message:
        payload['message'] = message

    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 18
0
    def handle_error(self, err):
        print(type(err))
        print(err)
        # Handle HTTPExceptions
        if isinstance(err, HTTPException):
            return jsonify({
                'detail':
                getattr(err, 'description',
                        HTTP_STATUS_CODES.get(err.code, ''))
            }), err.code
        #Handle validation error
        if isinstance(err, ValidationError) or isinstance(
                err, ModelValidationError) or isinstance(
                    err, PasswordValidationError):
            return jsonify({'detail': getattr(err, 'description',
                                              str(err))}), 400
        #Handle authorization issues
        jwt_err_types = list(
            map(lambda ty: getattr(jwt_errs, ty),
                filter(lambda x: not x.startswith("__"), dir(jwt_errs))))
        jwt_extended_err_types = list(
            map(
                lambda ty: getattr(jwt_extended_errs, ty),
                filter(lambda x: not x.startswith("__"),
                       dir(jwt_extended_errs))))
        if type(err) in jwt_err_types + jwt_extended_err_types + [
                AuthenticationFailedError
        ]:
            return jsonify({'detail': getattr(err, 'description',
                                              str(err))}), 401

        #Handle duplication
        if isinstance(err, NotUniqueError):
            expr = re.compile("(\{\s*.*\})")
            m = expr.findall(str(err))
            print(type(m[0]))
            str(err)
            return jsonify({
                'detail':
                getattr(
                    err, 'description',
                    f"There is a unique constraint violation. {m[0] if len(m)>0 else ''}"
                )
            }), 400
        # If msg attribute is not set,
        # consider it as Python core exception and
        # hide sensitive error info from end user
        if not getattr(err, 'message', None):
            return jsonify({'detail':
                            'Server has encountered some error'}), 500
        # Handle application specific custom exceptions
        return jsonify(**err.kwargs), err.http_status_code
Ejemplo n.º 19
0
def error(status_code, message=None):
    """Return the error specified by the status_code.

    If message is present, attach also it to the response.
    """
    payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown")}
    if message:
        payload["message"] = message

    response = jsonify(payload)
    response.status_code = status_code

    return response
Ejemplo n.º 20
0
def error_response(status_code, message=None):
    """构造错误响应数据"""
    # payload 根据状态码返回错误信息,未能识别的状态码默认为Unknown error
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    # 如果有消息则设置消息.
    if message:
        payload['message'] = message

    # 构造响应对象
    response = jsonify(payload)
    response.status_code = status_code

    return response
Ejemplo n.º 21
0
def create_response(status_code, message, details):
    header = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}

    if message:
        header['message'] = message

    if details:
        header['details'] = details

    response = jsonify(header)
    response.status_code = status_code

    return response
Ejemplo n.º 22
0
def error_response(status_code, message=None):
    """
    Return a response with message
    :param status_code: HTTP Status code in Integer.
    :param message: String to context the error.
    :return: Response object.
    """
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 23
0
    def get_title(self, status_code, pointer, error):
        """Get the title of the error to be returned to the user.

        Args:
            status_code (int): The status code of the error.
            pointer (list): A list of str (pointer segments) to the field which raised the initial errors.
            error (:drf_gh:`rest_framework.exceptions.ErrorDetail <rest_framework/exceptions.py>`): The DRF-provided
                detail of the error.

        Returns:
            str: The title of the message.
        """
        return HTTP_STATUS_CODES.get(status_code, None)
Ejemplo n.º 24
0
def error_response(status_code, message=None):
    """
    Return an error response in JSON format.

    status_code: X
    message: X
    """
    payload = {"error": HTTP_STATUS_CODES.get(status_code, "Unknown error")}
    if message:
        payload["message"] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 25
0
def error_response(status: int, message: Optional[str] = None) -> Response:
    """Helper function for returning more meaningful error messages.
    :param status: HTTP status code
    :param message: optional message
    """
    if type(status) is not int:
        status = status.code
    error = HTTP_STATUS_CODES.get(status, 'Unknown Error')

    if _wants_json_response():
        return _api_error_response(status, error, message)
    else:
        return _html_error_response(status, error, message)
Ejemplo n.º 26
0
    def __init__(self, status_code, message=None, details=None):
        super().__init__()

        error = HTTP_STATUS_CODES.get(status_code, "Unknown error")

        self.status_code = status_code
        self.payload = {"error": error}

        if message is not None:
            self.payload["message"] = message

        if details is not None:
            self.payload["details"] = details
Ejemplo n.º 27
0
def _get_response(exception):
    """
    Return a JSON Flask response object.

    The properties of the JSON object and the status code of the result are set
    based on the details of the exception.
    """
    response = {
        "statusCode": exception.code,
        "error": HTTP_STATUS_CODES.get(exception.code, "Unknown error"),
        "message": exception.description,
    }
    return jsonify(response), exception.code
Ejemplo n.º 28
0
def error_response(status_code, message=None):
    # HTTP_STATUS_CODES is a dictionary with the status codes as the keys and
    # a short description of each one for the value
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    # jsonify returns Flask Response object with default status code of 200
    # wraps dumps and sets media type correctly to application/json
    # Also a little more versatile than dumps
    response = jsonify(payload)
    # Reset status_code to correct passed in value (vs. default of 200)
    response.status_code = status_code
    return response
Ejemplo n.º 29
0
    def abort(self, status, error=None, encoder=True):
        (self.log.exception if self.app.debug and exc_info()[0] else
         self.log.error)('%r %s %s >> %s', status, request.method,
                         request.path, error
                         or HTTP_STATUS_CODES.get(status, 'Unknown Error'))

        if error:
            return abort(status,
                         description=error,
                         response=self.encoders[encoder].make_response(
                             dict(status=status, error=error), status=status))
        else:
            return abort(status)
Ejemplo n.º 30
0
    def handle_error(self, err):
        """
        This class overrides 'handle_error' method of 'Api' class ,
        to extend global exception handing functionality of 'flask-restful'
        and helps preventing writing unnecessary
        try/except block though out the application
        """
        logger.exception(err, stack_info=True)

        # Handle HTTPExceptions, the base exception for all Werkzeug exceptions
        if isinstance(err, HTTPException):
            return jsonify({
                'success':
                False,
                'message':
                getattr(err, 'description',
                        HTTP_STATUS_CODES.get(err.code, '')),
                'data': {
                    'type': 'error',
                    'class': err.__class__.__name__,
                    'base': 'HTTPException',
                    'source': 'werkzeug'
                }
            }), err.code

        if isinstance(err, ValidationError):
            resp = {
                'success': False,
                'message': err.messages,
                'data': {
                    'type': 'error',
                    'class': 'ValidationError',
                    'source': 'Serializer'
                }
            }
            return jsonify(resp), 400
        # If msg attribute is not set,
        # consider it as Python core exception and
        # hide sensitive error info from end user
        if getattr(err, 'message', None):
            return jsonify({
                'success': False,
                'message': 'Server has encountered some error'
            }), 500
        # Handle application specific custom exceptions
        try:
            err.kwargs['message'] = err.kwargs['msg']
            del (err.kwargs['msg'])
        except KeyError:
            pass
        return jsonify(**err.kwargs), err.http_status_code
Ejemplo n.º 31
0
 def log_request(self, *args):
     '''Use standard logging'''
     code = self.request.response_code
     if app.config['DEBUG']:
         message = '%s [%s: %s]' % (self.request.uri, code,
                 HTTP_STATUS_CODES.get(code, 'Unknown'))
     else:
         message = self.format_request(*args)
     if code < 404:
         logger.info(message)
     elif code < 500:
         logger.warn(message)
     else:
         logger.error(message)
Ejemplo n.º 32
0
def error_response(status_code, message=None):
    """
    Returns an API friendly error (as opposed to the standard html errors

    :param status_code: <int> http status code
    :param message: <str> message with extra information
    :return: returns http response with json payload and correct status code
    """
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 33
0
def response(code=200, data=None, error=None, msg=None):
    '''
    :param code: 状态码
    :param data: 返回数据
    :param error: 错误信息
    :param msg: 提示信息
    '''

    if code is not None and code >= 400:
        error = HTTP_STATUS_CODES.get(code, "unknown error")

    pay_load = {
        "code": code,
        "data": data,
        "err": error,
        "message": msg or HTTP_STATUS_CODES.get(code, "unknown error")
    }

    # with ttt_app.app_context():
    _res = jsonify(pay_load)
    _res.status_code = code

    return _res
Ejemplo n.º 34
0
def error(e):
    if isinstance(e, HTTPException):
        error_code = e.code
        error_desc = e.description
    else:
        error_code = 500
        error_desc = _("internal_error")
        app.log_exception(e)

    error_name = HTTP_STATUS_CODES.get(error_code, "Unknown Error")
    return render_template("error.html",
                           error_code=error_code,
                           error_name=error_name,
                           error_desc=error_desc), error_code
Ejemplo n.º 35
0
def response(status_code=200, data=None, message=None):
    if data == None and status_code == 200:
        status_code = 204

    pay_load = {
        "code": status_code,
        "message": message
        or HTTP_STATUS_CODES.get(status_code, "unknown code"),
        "data": data,
        "timestamp": int(time.time())
    }
    _response = jsonify(pay_load)
    _response.status_code = status_code
    return _response
Ejemplo n.º 36
0
    def __call__(self, environ, start_response):
        if "HTTP_USER_AGENT" not in environ:
            status_code = 403
            status = "%s %s" % (status_code,
                                HTTP_STATUS_CODES.get(status_code, ""))
            headers = [("Content-Type", "text/html")]
            start_response(status, headers)
            return ""
        user_agent = environ["HTTP_USER_AGENT"]
        path_info = environ["PATH_INFO"]
        print("middleware")
        print(environ)
        for k, v in environ.items():
            print("%s : %s" % (k, v))
            # print(v)
        if path_info == "/404":
            status = "404 %s" % HTTP_STATUS_CODES.get(404, "")
            headers = [("Content-Type", "text/html")]
            start_response(status, headers)
            return ""
        result = self.wsgi_app(environ, start_response)

        return result
Ejemplo n.º 37
0
def error_response(status_code, message=None):
    """错误响应 结构
    {
    "error": "short error description",
    "message": "error message (optional)"
    }
    
    """
    payload = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = status_code
    return response
Ejemplo n.º 38
0
def http_status_message(code):
    """Maps an HTTP status code to the textual status"""
    return HTTP_STATUS_CODES.get(code, '')
Ejemplo n.º 39
0
 def as_dict(self):
     return {
         'status': self.status_code,
         'message': HTTP_STATUS_CODES.get(self.status_code, '')
     }
Ejemplo n.º 40
0
 def name(self):
     return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
Ejemplo n.º 41
0
def http_status_message(code):
    return HTTP_STATUS_CODES.get(code, '')
Ejemplo n.º 42
0
 def as_dict(self):
     return {"status": self.status_code, "message": HTTP_STATUS_CODES.get(self.status_code, "")}