Consider this Flask app using the extension initialization pattern. What will be printed when the app runs?
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 'Hello, Flask!' with app.app_context(): print(type(db.engine)) return app app = create_app()
Think about when the database engine is created in the extension initialization pattern.
The db.init_app(app) call binds the SQLAlchemy extension to the Flask app. Inside the app context, db.engine is available and is an instance of SQLAlchemy's engine class.
Given this Flask app using the extension initialization pattern, what is the value of app.config['DEBUG'] after create_app() is called?
from flask import Flask from flask_mail import Mail mail = Mail() def create_app(): app = Flask(__name__) app.config['DEBUG'] = True mail.init_app(app) return app app = create_app() value = app.config['DEBUG']
Extension initialization does not change existing config values.
The DEBUG config is set before calling mail.init_app(app). The extension does not modify this config, so it remains True.
Choose the correct way to initialize a Flask extension using the extension initialization pattern (factory pattern).
Extension initialization pattern separates extension creation and app binding.
Option A correctly creates the extension instance first, then binds it to the app using init_app. This supports the factory pattern.
Given this code, why does accessing db.session raise an error?
from flask import Flask from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' @app.route('/') def index(): return str(db.session) if __name__ == '__main__': app.run()
Check if the extension was properly linked to the app.
The extension instance db was created but never initialized with app via init_app. Without this, db.session is not set up and accessing it raises an error.
Why do Flask developers use the extension initialization pattern (creating extension instances outside the app and calling init_app later)?
Think about app factories and multiple app instances.
The pattern allows creating extension instances once and initializing them with different Flask app instances later. This supports app factories and multiple apps sharing extensions.