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
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
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 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
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')
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
def handle_http_error(e): response = { 'meta': meta(e.code, HTTP_STATUS_CODES.get(e.code)), } return jsonify(response), e.code
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
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))
def http_status_message(code: int) -> str: """Maps an HTTP status code to the textual status :param code: """ return HTTP_STATUS_CODES.get(code, "")
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 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')
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
def error_response(status_code, message=None): response = { "code": status_code, "msg": HTTP_STATUS_CODES.get(status_code), "data": {} } return jsonify(response)
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)))
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
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
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
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
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
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
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
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
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 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')
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
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)
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
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') }
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
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
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 }
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)
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
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)
def http_status_message(code): """Maps an HTTP status code to the textual status""" return HTTP_STATUS_CODES.get(code, '')
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
def as_dict(self): return { 'status': self.status_code, 'message': HTTP_STATUS_CODES.get(self.status_code, '') }
def name(self): return HTTP_STATUS_CODES.get(503, 'Service Unavailable')
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
def http_status_message(code): return HTTP_STATUS_CODES.get(code, '')
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
def as_dict(self): return {"status": self.status_code, "message": HTTP_STATUS_CODES.get(self.status_code, "")}