0
0
Flaskframework~5 mins

Extension initialization pattern in Flask - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the Flask extension initialization pattern?
It allows you to create an extension instance separately and initialize it later with a Flask app. This helps organize code and supports multiple app instances.
Click to reveal answer
beginner
How do you create a Flask extension instance without binding it to an app immediately?
You create the extension object by calling its constructor without passing the app, for example: db = SQLAlchemy().
Click to reveal answer
beginner
What method do you call to bind a Flask extension instance to an app later?
You call the init_app(app) method on the extension instance, passing the Flask app object.
Click to reveal answer
intermediate
Why is the extension initialization pattern useful in Flask applications?
It supports creating extensions before the app exists, helps with testing, and allows sharing one extension instance across multiple apps.
Click to reveal answer
beginner
Show a simple example of the Flask extension initialization pattern using SQLAlchemy.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()  # create extension instance

def create_app():
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
    db.init_app(app)  # initialize with app
    return app
Click to reveal answer
What does the init_app() method do in Flask extensions?
ADeletes the extension instance
BCreates a new Flask app
CBinds the extension instance to a Flask app
DRuns the Flask app
Why might you create a Flask extension instance without passing the app immediately?
ABecause Flask requires it
BTo delay app creation and support multiple apps
CTo avoid using extensions
DTo make the app run faster
Which of these is a benefit of the extension initialization pattern?
ASupports multiple Flask apps sharing one extension instance
BPrevents using extensions
CAutomatically creates a database
DRemoves the need for configuration
In the extension initialization pattern, when is the extension instance typically created?
ABefore the Flask app is created
BAfter the app runs
COnly inside the app factory
DWhen the server stops
What is the common name for the Flask pattern that uses init_app()?
ADecorator pattern
BBlueprint pattern
CSingleton pattern
DExtension initialization pattern
Explain the Flask extension initialization pattern and why it is useful.
Think about how you can prepare an extension before the app exists.
You got /4 concepts.
    Write a simple example showing how to use the extension initialization pattern with a Flask app and SQLAlchemy.
    Remember to separate extension creation and app creation.
    You got /5 concepts.