Performance: Application factory pattern
This pattern affects the initial load time and memory usage by controlling when and how the Flask app and its extensions are created.
from flask import Flask def create_app(): app = Flask(__name__) @app.route('/') def home(): return 'Hello World!' return app if __name__ == '__main__': app = create_app() app.run()
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello World!' if __name__ == '__main__': app.run()
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| App created at import | N/A | N/A | N/A | [X] Bad |
| App created via factory on run | N/A | N/A | N/A | [OK] Good |
application factory pattern in Flask?create_app that creates a Flask instance and returns it.print(app.config['DEBUG']) output?def create_app():
app = Flask(__name__)
app.config['DEBUG'] = True
return app
app = create_app()
print(app.config['DEBUG'])create_app creates a Flask app and sets app.config['DEBUG'] = True before returning the app.create_app(), the returned app has DEBUG set to True. So printing it outputs True.def create_app():
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello'
return app
app = create_app()
app.run()app.run() outside the factory is normal to start the server. The code is valid and will run correctly.app.register_blueprint(). Two options do this correctly, while one incorrectly calls main_bp.register_blueprint(app).db = SQLAlchemy()) and then call db.init_app(app). The option that does db = SQLAlchemy(); db.init_app(app) follows this correctly. The other factory option with correct blueprint registration uses db = SQLAlchemy(app), which binds it directly to the app and is less flexible.Pass the test and this pattern moves unknown