Solution
from os import getenv
from flask import Flask, make_response, jsonify
from flask_cors import CORS
from app.extensions import db, migrate, socketio
def create_app(blueprints=None) -> Flask:
"""
Builds up a Flask app and return it to the caller
:param blueprints: a custom list of Flask blueprints
:return: Flask app object
"""
if blueprints is None:
blueprints = DEFAULT_BLUEPRINTS
app = Flask(__name__)
configure_app(app)
configure_extensions(app)
configure_error_handlers(app)
with app.app_context():
# Import blueprints here
DEFAULT_BLUEPRINTS = [] # list of the blueprints here
if blueprints is None:
blueprints = DEFAULT_BLUEPRINTS
configure_blueprints(app, blueprints)
print("Returning app...")
return app
def configure_app(app):
app.config.from_object(getenv('APP_SETTINGS', "config.DevelopmentConfig"))
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
def configure_blueprints(app, blueprints):
for blueprint in blueprints:
app.register_blueprint(blueprint)
def configure_extensions(app):
db.init_app(app)
migrate.init_app(app, db, directory="migrations")
socketio.init_app(app, cors_allowed_origins='*')
CORS(app, resources={r"*": {"origins": "*"}})
def configure_error_handlers(app):
@app.errorhandler(404)
def not_found(error):
return make_response(jsonify({'error': 'Not found'}), 404)
# Return validation errors as JSON
@app.errorhandler(422)
@app.errorhandler(400)
def handle_error(err):
headers = err.data.get("headers", None)
messages = err.data.get("messages", ["Invalid request."])
if headers:
return jsonify({"errors": messages}), err.code, headers
else:
return jsonify({"errors": messages}), err.code