def create_app(environment=None): app = Flask('veritrans') app.url_map.converters['ObjectId'] = BSONObjectIdConverter # Config app for environment if not environment: environment = os.environ.get('BACKEND_ENVIRONMENT', 'Prod') app.config.from_object('core.api.settings.%s' % environment) # convert exceptions to JSON def make_json_error(ex): response = jsonify( message=str(ex) ) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response for code in default_exceptions.items(): app.error_handler_spec[None][code] = make_json_error from core.api.views.endpoints import api app.register_module(api) return app
def _jsonify_http_errors(self, app): """Force HTTP errors returned as JSON instead of default HTML.""" status_field = app.config['JSON_STATUS_FIELD_NAME'] def _handler(error, status_code, reason, default_description): response = { 'reason': reason, 'description': default_description, } if app.config['JSON_ADD_STATUS']: response[status_field] = status_code if isinstance(error, HTTPException) and error.description: response['description'] = error.description return json_response(status_code, data_=response) for code, exc in default_exceptions.items(): if issubclass(exc, HTTPException): app.register_error_handler( code, partial( _handler, status_code=code, reason=exc().name, default_description=exc.description, ))
def create_app(environment=None): """ Create an app instance """ app = Flask('core') # Allow CORS for all domains on all routes CORS(app) # Config app for environment if not environment: environment = os.environ.get('BACKEND_ENVIRONMENT', 'Dev') app.config.from_object('core.api.settings.%s' % environment) # convert exceptions to JSON def make_json_error(ex): response = jsonify( message=str(ex) ) response.status_code = ( ex.code if isinstance(ex, HTTPException) else 500 ) return response for code in default_exceptions.items(): app.error_handler_spec[None][code] = make_json_error from core.api.views.endpoints import api app.register_module(api) API.app = app
def _jsonify_http_errors(self, app): """Force HTTP errors returned as JSON instead of default HTML.""" status_field = app.config['JSON_STATUS_FIELD_NAME'] def _handler(error, status_code, reason, default_description): response = { 'reason': reason, 'description': default_description, } if app.config['JSON_ADD_STATUS']: response[status_field] = status_code if isinstance(error, HTTPException) and error.description: response['description'] = error.description return json_response(status_code, data_=response) for code, exc in default_exceptions.items(): if issubclass(exc, HTTPException): app.register_error_handler(code, partial( _handler, status_code=code, reason=exc().name, default_description=exc.description, ))
def create_app(): app = flask.Flask(__name__) for code, exception in default_exceptions.items(): app.errorhandler(code)(_handle_http_exception) app.errorhandler(Exception)( _handle_http_exception) # to handle all exceptions in debug mode return app
def init_errors(flask_app, config): ''' Initialize error handlers. ''' def http_error_handler(error): ''' An error handler that will convert errors to JSON format if necessary. ''' if not isinstance(error, HTTPException): raise error #TODO Should use a real mime parser here… mimetype = request.headers.get('accept', '').strip() if hasattr(error, 'description'): description = error.description else: description = str(error) if mimetype.startswith('application/json'): response = jsonify(message=description) else: response = make_response(description + '\n\n') response.headers['Content-type'] = 'text/plain' response.status_code = error.code return response http_status_codes = [code for code, obj in default_exceptions.items()] for http_status_code in http_status_codes: flask_app.errorhandler(http_status_code)(http_error_handler)
def _initialize_global_exception_handler(app): for code, ex in default_exceptions.items(): app.errorhandler(code)(build_error_response) @app.errorhandler(404) def _unhandled_any_error(e): """ Global, any-unhandled-exception handler. Returns API error JSON response. """ return build_error_response(CustomLogException(e)) @app.errorhandler(500) def _unhandled_any_error(e): """ Global, any-unhandled-exception handler. Returns API error JSON response. """ return build_error_response(CustomLogException(e)) @app.errorhandler(Exception) def _unhandled_any_error(e): """ Global, any-unhandled-exception handler. Returns API error JSON response. """ return build_error_response(CustomLogException(e)) @app.errorhandler(FlaskProjectLogException) def _unhandled_any_error(e): """ Global, any-unhandled-exception handler. Returns API error JSON response. """ return build_error_response(CustomLogException(e))
def test_create_test_app_errors(self): for code, error in default_exceptions.items(): response = self.unbound_app.get(f'/error/{error.__name__}') self.assertEqual(response.status_code, code) response_str = response.data.decode() if response_str: # one exception has no message self.assertIn(TEST_MESSAGE, response_str)
def init_errorhandlers(self): self.app.errorhandler(Exception)(common_exception_handler) self.app.errorhandler(BaseException)(base_exception_handler) for code, ex in default_exceptions.items(): self.app.errorhandler(code)(http_exception_handler) return self
def test_bind_json_error_handlers_all_werkzeug_errors(self): for code, error in default_exceptions.items(): name = error.__name__ response = self.bound_app.get(f'/error/{name}') self.assertEqual(response.status_code, code) if code != 412: # I cannot figure out why this exception is so much trouble response_json = json.loads(response.data) self.assertEqual(response_json['error_type'], name) self.assertEqual(response_json['status_code'], code) self.assertEqual(response_json['text'], TEST_MESSAGE)
def register_blueprints(): import errorhandler from model.url import app_url, db as db_url for code, ex in default_exceptions.items(): app.errorhandler(code)(errorhandler.create_message_error) app.register_blueprint(app_url, url_prefix='/url') app.config["SQLALCHEMY_DATABASE_URI"] = config.SQLALCHEMY_DATABASE_URI app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False db_url.init_app(app) with app.app_context(): db_url.create_all()
def init_app(self, app): """ :param app: """ self.app = app self.register(HTTPException) for code, _ in default_exceptions.items(): self.register(code) self.register(Exception)
def create_web_app() -> Flask: """Create a new :class:`.Flask` app and define the API.""" app = Flask("fourohfour") Base(app) # Override the default error handlers to provide content negotation. for _, error in default_exceptions.items(): app.errorhandler(error)(content_aware_exception_handler) app.route('/healthz')(healthz) app.route('/')(echo) return app
def make_app(import_name, **kwargs): def error_handler(ex): response = jsonify(message=str(ex)) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response application = Flask(import_name, **kwargs) for code in default_exceptions.items(): application.error_handler_spec[code] = error_handler return application
def init_app(self, app, debug=None): self.app = app if debug is not None: self.debug = debug if self.debug is None: self.debug = app.debug self.register_with_handler(HTTPException) for code, v in default_exceptions.items(): self.register_with_handler(code) self.register_with_handler(v) if not self._to_do: return for exception_or_code, handler in self._to_do: self.app.errorhandler(exception_or_code)(handler)
def make_json_webapi(app_name, **kwargs): def make_json_error(ex): error = str(ex) return make_default_response(success=False, errors=[error]) flask_app = Flask(app_name) for exception in default_exceptions.items(): flask_app.register_error_handler(exception[0], make_json_error) flask_app.register_error_handler(Exception, make_json_error) @flask_app.after_request def set_content_type(response): if not response.mimetype == 'image/png': response.headers["Content-Type"] = "application/json" return response return flask_app
def init_app(self, app): """ Initialize the extension with any application-level configuration requirements. This is where we register the Werkzeug `HTTPException` class along with all the other default exception codes. """ self.app = app # Register the default HTTP codes to be handled by our exception # handler. for code, _ in default_exceptions.items(): self.register(code) if not hasattr(self.app, 'extensions'): self.app.extensions = {} self.app.extensions['apiexceptions'] = self
def handle_http_exceptions(self): def handler(e): LOGGER.error("Getted http exception: %s", e, exc_info=True, extra={"meta": e}) resp = jsonify({ "error": e.name, "code": e.code, "description": e.description }) resp.status_code = e.code return resp for code, ex in default_exceptions.items(): self.app.errorhandler(code)(handler) return self
def _initialize_errorhandlers(app): from flask import jsonify from werkzeug.exceptions import default_exceptions, InternalServerError def _handle_http_exception(error): """JSON Exceptions""" status_code = error.code if hasattr(error, 'code') else 500 description = error.description if hasattr( error, 'description') else InternalServerError.description return jsonify({ 'code': status_code, 'message': str(error), 'description': description }), status_code # Catch all exceptions app.register_error_handler(Exception, _handle_http_exception) # Catch all HTTPExceptions for code, ex in default_exceptions.items(): app.errorhandler(code)(_handle_http_exception)
def handle_http_exceptions(self): def handler(e): LOGGER.error( "Getted http exception: %s", e, exc_info=True, extra={"meta": e} ) resp = jsonify({ "error": e.name, "code": e.code, "description": e.description }) resp.status_code = e.code return resp for code, ex in default_exceptions.items(): self.app.errorhandler(code)(handler) return self
def _initialize_global_exception_handler(app): # Following does not work: https://github.com/mitsuhiko/flask/issues/941 # # @app.errorhandler(HTTPException) # def unhandled_http_error(e): # return build_error_response(e) # # It was a bug, it was fixed and merged but it will not be in Flask before # 1.0 (now is v0.10, there will be no version 0.11) # # We implement sugested workaround: for code, ex in default_exceptions.items(): app.errorhandler(code)(build_error_response) @app.errorhandler(Exception) def _unhandled_any_error(e): """ Global, any-unhandled-exception handler. Returns API error JSON response. """ return build_error_response(e)
def __init__(self, app=None): if app: self.app = app self.register(HTTPException) for code, v in default_exceptions.items(): self.register(code)
if isinstance(sys_error, HTTPException): #or isinstance(sys_error, APIError): message = sys_error.description status_code = sys_error.code else: message = str(sys_error) status_code = 500 error_info = traceback.format_exc() log_all_exceptions(logger) # This should be skipped depending on config if(CFG_OBJ.get('DEBUG') == True): print(error_info) return make_response(jsonify(message=message), status_code) for error in default_exceptions.items(): app.error_handler_spec[None][error] = system_error_handler app.error_handler_spec[None][error[0]] = system_error_handler if __name__ == '__main__': # setup logger log_type = CFG_OBJ.get('LOGGING.TYPE') log_path = CFG_OBJ.get('LOGGING.PATH') logger = LoggerFactory.create(log_type, log_path) # log the app start message with a timestamp separator = '*' * 80 logger.log("\n" + separator) logger.log("Application Starting :: {}".format(datetime.now())) logger.log("\n" + separator)
def bind_json_error_handlers(app): for code, error in default_exceptions.items(): app.errorhandler(code)(handle_error)
def init_app(self, app): app.register_error_handler(Exception, self.handler) for code, _ in default_exceptions.items(): app.register_error_handler(code, self.handler)
def init_app(self): self.register(HTTPException) for code, v in default_exceptions.items(): self.register(code)
return func return deco def get_handlers() -> List[Tuple[Type[HTTPException], Callable]]: """ Get a list of registered exception handlers. Returns ------- list List of (:class:`.HTTPException`, callable) tuples. """ return _handlers def handle_exception(error: HTTPException) -> Response: """Render a generic error handler.""" rendered = render_template("base/exception.html", error=error, pagetitle=f"{error.code} {error.name }") response: Response = make_response(rendered, error.code) return response # Generate handlers programmatically from the built-in Werkzeug HTTP # exceptions. for code, exception_type in default_exceptions.items(): handler(exception_type)(handle_exception)
'description': getattr(error, 'message', None) or getattr(error, 'description', None) or str(error), 'code': code } }) except: context = jsonify({ 'error': { 'description': error.get_body(), 'code': code, } }) return context, code for code, error in default_exceptions.items(): app.register_error_handler(error, default_error_handler) default_view = default.DefaultView.as_view('default') app.add_url_rule('/', view_func=default_view, methods=['GET']) account_view = account.AccountView.as_view('account') app.add_url_rule('/accounts', view_func=account_view, methods=['POST']) account_authentication_view = account.AccountAuthenticationView.as_view('account_authentication') app.add_url_rule('/accounts/authentications', view_func=account_authentication_view, methods=['GET', 'POST']) evaluation_view = evaluation.EvaluationView.as_view('evaluation') app.add_url_rule('/evaluations', view_func=evaluation_view, methods=['POST'])
mimetypes.init() app = Flask(__name__) app.config.from_object('config') app.static_url_path = app.config.get('STATIC_FOLDER') app.jinja_env.trim_blocks = True app.jinja_env.lstrip_blocks = True db = SQLAlchemy(app) migrate = Migrate(app, db) manager = Manager(app) manager.add_command('db', MigrateCommand) lm = LoginManager(app) jsglue = JSGlue(app) from links import helpers, views, models, forms with app.test_request_context(): lm.login_view = url_for('login') # fixme: It's impossible to catch HTTPException. Flask Bug #941 (https://github.com/pallets/flask/issues/941) from werkzeug.exceptions import default_exceptions for code, ex in default_exceptions.items(): app.errorhandler(code)(views.any_error)
# Creates a JSON-oriented Flask app. # # All error responses that you don't specifically # manage yourself will have application/json content # type, and will contain JSON like this (just an example): # # { "message": "405: Method Not Allowed" } def make_json_error(ex): response = jsonify(message=str(ex)) response.status_code = (ex.code if isinstance(ex, HTTPException) else 500) return response for code in default_exceptions.items(): app.error_handler_spec[None][code] = make_json_error @app.errorhandler(Exception) def error500(e): logger.exception(e) error_code = 500 return jsonify(error=error_code, message=str(e)), error_code # # Routes #
message = sys_error.description status_code = sys_error.code else: message = str(sys_error) status_code = 500 error_info = traceback.format_exc() log_all_exceptions(logger) # This should be skipped depending on config if (CFG_OBJ.get('DEBUG') == True): print(error_info) return make_response(jsonify(message=message), status_code) for error in default_exceptions.items(): app.error_handler_spec[None][error] = system_error_handler app.error_handler_spec[None][error[0]] = system_error_handler if __name__ == '__main__': # setup logger log_type = CFG_OBJ.get('LOGGING.TYPE') log_path = CFG_OBJ.get('LOGGING.PATH') logger = LoggerFactory.create(log_type, log_path) # log the app start message with a timestamp separator = '*' * 80 logger.log("\n" + separator) logger.log("Application Starting :: {}".format(datetime.now())) logger.log("\n" + separator)