Пример #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
Пример #2
0
def error_response(status_code, message=None):
    resbody = {'error': HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        resbody['message'] = message
    response = jsonify(resbody)
    response.status_code = status_code
    return response
Пример #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
Пример #4
0
def abort_error(code, message=None, **kwargs):
    if message is None:
        message = HTTP_STATUS_CODES.get(code, '')

    response = jsonify(code=code, msg=message, data={}, **kwargs)
    response.status_code = code
    return response
Пример #5
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
Пример #6
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')
Пример #7
0
def make_json_response(message, status_code=200, status=None):
    """Convenience function to create standard JSON response."""
    if status is None:
        status = HTTP_STATUS_CODES.get(status_code, '')
    response = jsonify(message=message, statusCode=status_code, status=status)
    response.status_code = status_code
    return response
Пример #8
0
def handle_http_error(e):

    response = {
        'meta': meta(e.code, HTTP_STATUS_CODES.get(e.code)),
    }
    
    return jsonify(response), e.code
Пример #9
0
def error_response(status_code, message=None):
    answer = {'error': HTTP_STATUS_CODES.get(status_code, 'Error')}
    if message:
        answer['message'] = message
    response = jsonify(answer)
    response.status_code = status_code
    return response
Пример #10
0
def abort(ex, *, json=None, query=None):
    from flask import abort, make_response
    from werkzeug.http import HTTP_STATUS_CODES
    from werkzeug.exceptions import default_exceptions

    json = json or {}
    query = query or {}

    if isinstance(ex, Response):
        try:
            if ("message" in ex.json() and len(json) == 0
                    and ex.json()["message"] is not None
                    and ex.json()["message"] != ""):
                json = ex.json()["messsage"]
        except JSONDecodeError:
            pass
        ex = default_exceptions[ex.status_code]

    payload = dict(
        code=ex.code,
        message=ex.description,
        status=HTTP_STATUS_CODES.get(ex.code, "Unknown Error"),
    )
    if len(json) > 0:
        payload.setdefault("errors", {})["json"] = json
    if len(query) > 0:
        payload.setdefault("errors", {})["query"] = query

    abort(make_response(payload, ex.code))
Пример #11
0
def http_status_message(code: int) -> str:
    """Maps an HTTP status code to the textual status

    :param code:

    """
    return HTTP_STATUS_CODES.get(code, "")
Пример #12
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
Пример #13
0
def get_reason_phrase(status_code: int) -> str:
    """A helper function to get the reason phrase of the given status code.

    Arguments:
        status_code: A standard HTTP status code.
    """
    return HTTP_STATUS_CODES.get(status_code, 'Unknown error')
Пример #14
0
def error_response(status_code, message=None):
    """
        Function to send a custom error response in case an API is used
        The response is composed of a status code and optionaly a message
        Those two data are input ones

        :param status_code: the status code that will be returned
        :type status_code: int

        :param message: the error message that will be returned
        :type message: None | str

        :return: the error response
        :rtype: flask.wrappers.Response
    """

    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
Пример #15
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')
Пример #16
0
def error_response(status_code, message=None):
    response = {
        "code": status_code,
        "msg": HTTP_STATUS_CODES.get(status_code),
        "data": {}
    }
    return jsonify(response)
Пример #17
0
    def error(self, status_code, request, message=None):
        """Handle error response.

        :param int status_code:
        :param request:
        :return:

        """
        status_code_text = HTTP_STATUS_CODES.get(status_code, 'http error')
        status_error_tag = status_code_text.lower().replace(' ', '_')
        custom_response_map = {
            404:
            self.make_error_response(
                status_error_tag,
                'The requested URL {} was not found on this service.'.format(
                    request.path)),
            400:
            self.make_error_response(status_error_tag, message),
            405:
            self.make_error_response(
                status_error_tag,
                'The requested URL {} was not allowed HTTP method {}.'.format(
                    request.path, request.method)),
        }
        return self._raw_response(
            status_code,
            custom_response_map.get(
                status_code,
                self.make_error_response(status_error_tag, message
                                         or status_code_text)))
Пример #18
0
def bad_request(message):
    payload = {'error': HTTP_STATUS_CODES.get(400, 'Unknown error')}
    if message:
        payload['message'] = message
    response = jsonify(payload)
    response.status_code = 400
    return response
Пример #19
0
def api_abort(code, message=None, **kwargs):
    if message is None:
        message = HTTP_STATUS_CODES.get(code, '')

    response = jsonify(code=code, message=message, **kwargs)
    response.status_code = code
    return response
Пример #20
0
def api_message(http_code, code=None, message=None, data=None, **kwargs):
    if message is None:
        message = HTTP_STATUS_CODES.get(http_code, '')
    if data is None:
        response = dict(code=code, message=message, **kwargs)
    else:
        response = dict(code=code, message=message, data=data, **kwargs)
    return response, http_code
Пример #21
0
def error_response(status_code, message=None):
    #dictionary that provides a short descriptive name for each HTTP 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
Пример #22
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
	response.headers.add('Access-Control-Allow-Origin', '*')
	return response
Пример #23
0
def error_response(error):
    payload = {'error': HTTP_STATUS_CODES.get(error.status_code,
               'Unknown error')}
    if error.description:
        payload['message'] = error.description
    response = jsonify(payload)
    response.status_code = error.status_code
    return response
Пример #24
0
 def success_response(self):
     payload = {
         'message': HTTP_STATUS_CODES.get(self.status_code),
         'data': self.data
     }
     response = jsonify(payload)
     response.status_code = self.status_code
     return response
Пример #25
0
def error_response(status_code: int,
                   messages: Union[str, List, Dict] = None) -> Response:
    error_status = HTTP_STATUS_CODES.get(status_code, "Unknown error")
    response = jsonify({"success": False, "errors": messages or error_status})
    response.status_code = status_code

    secure_headers.flask(response)
    return response
Пример #26
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
Пример #27
0
    def status(self):
        """Returns the HTTP status line for the error response

        :return: The HTTP status line for the error response
        :rtype: str
        """
        return str(self.status_code) + ' ' + HTTP_STATUS_CODES.get(
            self.status_code, 'Unknown Error')
Пример #28
0
def error_response(status_code, message=None):
    """Construct an API error response."""
    response = jsonify({
        "error": HTTP_STATUS_CODES.get(status_code, "Unkown Error"),
        "message": message
    })
    response.status_code = status_code
    return response
Пример #29
0
    def handle_error(self, environ, ue):
        if ue.status_code == 404:
            return self._not_found_response(environ, ue.url)

        else:
            status = str(ue.status_code) + ' ' + HTTP_STATUS_CODES.get(ue.status_code, 'Unknown Error')
            return self._error_response(environ, ue.url, ue.msg,
                                        status=status)
Пример #30
0
def error_response(status_code, message=None):
    """Return a JSON object of the HTTP status code and optional message"""
    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
Пример #31
0
 def get_body(self):
     return (u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n'
             u'<title>%(code)s %(name)s</title>\n'
             u'<h1>%(name)s</h1>\n') % {
                 'code': self.status_code,
                 'name': HTTP_STATUS_CODES.get(self.status_code,
                                               'Unknown Error')
             }
Пример #32
0
def error_response(status_code, message=None):
    payload = {"error": HTTP_STATUS_CODES.get(status_code, 'Unknown error')}
    if message:
        payload["message"] = message
    app.logger.error("Error: " + message)
    response = jsonify(payload)
    response.status_code = status_code
    return response
Пример #33
0
def error_response(status_code: int, message: str = None) -> Response:
    error_dict: Dict[str, str] = dict()
    error_dict['error'] = HTTP_STATUS_CODES.get(status_code, 'Unknown error')
    if message:
        error_dict['message'] = message
    response: Response = jsonify(error_dict)
    response.status_code = status_code
    return response
Пример #34
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
     }
Пример #35
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)
Пример #36
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
Пример #37
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)
Пример #38
0
def http_status_message(code):
    """Maps an HTTP status code to the textual status"""
    return HTTP_STATUS_CODES.get(code, '')
Пример #39
0
    raise BadRequest
必须
    raise ApiError
    return make_api_resp()
"""
@app.errorhandler(ApiError)
def error_handler(error):
    return api_error_handler(error)

from werkzeug.exceptions import HTTPException, MethodNotAllowed
from werkzeug.http import HTTP_STATUS_CODES

def default_error_handler(error):
    return make_api_resp(status_code=error.code, msg=error.name)

for status_code in HTTP_STATUS_CODES.keys():
    app.error_handler_spec[None][status_code] = default_error_handler


"""设置前处理和后处理"""
@app.before_request
def before_request():
    """如果HTTP Body为Json数据,需要设置Header
        Content-Type: application/json
    """
    logger.info(Logger.dumps(t='req'))
    request.on_json_loading_failed = on_json_loading_failed

@app.after_request
def after_request(resp):
    return resp
Пример #40
0
 def as_dict(self):
     return {
         'status': self.status_code,
         'message': HTTP_STATUS_CODES.get(self.status_code, '')
     }
Пример #41
0
 def name(self):
     return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
Пример #42
0
        def message_for_failed_should(self):
            message = 'Expected the status code {0}, but got {1}.'.format(
                      status, self._actual
                      )
            if self._response_data:
                response = 'Response Data:\n"{0}"'.format(self._response_data)
                message = '\n'.join([message, response])
            return message

        def message_for_failed_should_not(self):
            return 'Expected the status code not to be {0}'.format(status)
    return Checker


# Make be_xxx matchers for all the status codes
_status_codes = HTTP_STATUS_CODES.keys()
for code in _status_codes:
    matcher(make_status_checker('be', code))
    matcher(make_status_checker('abort', code))
    matcher(make_status_checker('return', code))


@matcher
class RedirectMatcher(object):
    ''' A matcher to check for redirects '''
    name = 'redirect_to'

    def __call__(self, location):
        self._expected = 'http://localhost' + location
        self._status_ok = True
        return self
Пример #43
0
def http_status_message(code):
    return HTTP_STATUS_CODES.get(code, '')
Пример #44
0
from typing import Iterable, List, Tuple

from werkzeug.http import HTTP_STATUS_CODES

from apistar import http

__all__ = ['WSGIEnviron', 'WSGIResponse']


STATUS_CODES = {
    code: "%d %s" % (code, msg)
    for code, msg in HTTP_STATUS_CODES.items()
}

ACCESS_CONTROL_ALLOW_ORIGIN = 'Access-Control-Allow-Origin'

WSGIEnviron = http.WSGIEnviron


class WSGIResponse(object):
    __slots__ = ('status', 'headers', 'iterator')

    def __init__(self,
                 status: str,
                 headers: List[Tuple[str, str]],
                 iterator: Iterable[bytes]) -> None:
        self.status = status
        self.headers = headers
        self.iterator = iterator

    @classmethod
Пример #45
0
 def as_dict(self):
     return {"status": self.status_code, "message": HTTP_STATUS_CODES.get(self.status_code, "")}