Performance: Extension initialization pattern
This pattern affects the app startup time and memory usage by controlling when and how extensions are initialized.
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def create_app(): app = Flask(__name__) db.init_app(app) return app
from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) # In each blueprint file from app import db # Using db directly without app factory pattern
| Pattern | Extension Setup Calls | Memory Usage | Startup Time | Verdict |
|---|---|---|---|---|
| Direct init with app instance | Multiple if app recreated | Higher due to repeated setups | Slower due to repeated init | [X] Bad |
| Lazy init with init_app in factory | Single call per extension | Lower, reused instances | Faster startup | [OK] Good |
init_app() method in Flask extensions?init_app()init_app() connects extension to app [OK]init_app(app) to bindinit_app() with the app to initialize the extension./?
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
def create_app():
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
db.init_app(app)
@app.route('/')
def index():
return 'DB Initialized'
return app
app = create_app()
db extension is created outside and initialized inside create_app() with db.init_app(app)./ returns the string 'DB Initialized'. Since the app and extension are properly set up, this will work.from flask import Flask
from flask_mail import Mail
mail = Mail()
def create_app():
app = Flask(__name__)
mail.init_app()
return app
init_app() method requires the Flask app instance as an argument.mail.init_app() is called without passing app, causing an error.db and login_manager inside the factory?create_app(), call init_app(app) on each extension to bind them to the app.Pass the test and this pattern moves unknown