Bird
Raised Fist0
Flaskframework~20 mins

Extension initialization pattern in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Extension Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Flask extension initialization code?

Consider this Flask app using the extension initialization pattern. What will be printed when the app runs?

Flask
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()
A<class 'flask_sqlalchemy.SQLAlchemy'>
B<class 'sqlalchemy.engine.base.Engine'>
CNone
DAttributeError: 'SQLAlchemy' object has no attribute 'engine'
Attempts:
2 left
💡 Hint

Think about when the database engine is created in the extension initialization pattern.

❓ state_output
intermediate
1:30remaining
What is the value of app.config['DEBUG'] after initialization?

Given this Flask app using the extension initialization pattern, what is the value of app.config['DEBUG'] after create_app() is called?

Flask
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']
ANone
BFalse
CTrue
DKeyError
Attempts:
2 left
💡 Hint

Extension initialization does not change existing config values.

📝 Syntax
advanced
2:00remaining
Which option correctly initializes a Flask extension with the factory pattern?

Choose the correct way to initialize a Flask extension using the extension initialization pattern (factory pattern).

A
db = SQLAlchemy()

app = Flask(__name__)
db.init_app(app)
B
db = SQLAlchemy(app)

app = Flask(__name__)

# extension initialized inline
C
app = Flask(__name__)
db = SQLAlchemy(app)

# extension initialized after app creation
D
app = Flask(__name__)
db = SQLAlchemy()

# extension initialized without init_app
Attempts:
2 left
💡 Hint

Extension initialization pattern separates extension creation and app binding.

🔧 Debug
advanced
2:30remaining
Why does this Flask app raise an error when accessing db.session?

Given this code, why does accessing db.session raise an error?

Flask
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()
AFlask app context is missing when accessing db.session
BSQLALCHEMY_DATABASE_URI is invalid, causing session error
Cdb.session requires manual creation before use
Ddb.init_app(app) was not called, so db.session is uninitialized
Attempts:
2 left
💡 Hint

Check if the extension was properly linked to the app.

🧠 Conceptual
expert
3:00remaining
What is the main advantage of the Flask extension initialization pattern?

Why do Flask developers use the extension initialization pattern (creating extension instances outside the app and calling init_app later)?

AIt allows creating multiple Flask apps sharing the same extension instance without re-instantiating it
BIt improves runtime performance by caching extension objects globally
CIt automatically configures extensions without needing app context
DIt prevents extensions from being used outside the Flask app
Attempts:
2 left
💡 Hint

Think about app factories and multiple app instances.

Practice

(1/5)
1. What is the main purpose of the init_app() method in Flask extensions?
easy
A. To initialize the extension with a Flask app instance after creation
B. To create a new Flask app instance
C. To run the Flask app server
D. To define routes inside the Flask app

Solution

  1. Step 1: Understand extension creation

    Extensions are created separately from the Flask app to keep code organized.
  2. Step 2: Role of init_app()

    This method connects the extension to the Flask app instance, usually inside a factory function.
  3. Final Answer:

    To initialize the extension with a Flask app instance after creation -> Option A
  4. Quick Check:

    init_app() connects extension to app [OK]
Hint: Remember: create extension first, then call init_app() [OK]
Common Mistakes:
  • Thinking init_app() creates the app
  • Confusing init_app() with running the server
  • Trying to define routes inside init_app()
2. Which of the following is the correct way to initialize a Flask extension using the extension initialization pattern?
easy
A. ext.init_app(app)
B. ext = Extension(app)
C. ext = Extension(); ext.init_app(app)
D. app = Flask(); ext = Extension(app); ext.init_app()

Solution

  1. Step 1: Create extension without app

    Extensions are first created without passing the app instance.
  2. Step 2: Call init_app(app) to bind

    After creation, call init_app() with the app to initialize the extension.
  3. Final Answer:

    ext = Extension(); ext.init_app(app) -> Option C
  4. Quick Check:

    Separate creation and init with app [OK]
Hint: Create extension first, then call init_app(app) [OK]
Common Mistakes:
  • Passing app to constructor directly
  • Calling init_app() without app argument
  • Calling init_app() before creating extension
3. Given this code snippet inside a Flask app factory, what will be the output when accessing the route /?
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()
medium
A. 404 Not Found
B. AttributeError: 'NoneType' object has no attribute 'route'
C. RuntimeError: application not registered on db instance
D. DB Initialized

Solution

  1. Step 1: Check extension initialization

    The db extension is created outside and initialized inside create_app() with db.init_app(app).
  2. Step 2: Confirm route and return value

    The route / returns the string 'DB Initialized'. Since the app and extension are properly set up, this will work.
  3. Final Answer:

    DB Initialized -> Option D
  4. Quick Check:

    Proper init_app() means route works [OK]
Hint: If init_app() called, extension works and route returns expected output [OK]
Common Mistakes:
  • Forgetting to call init_app(app)
  • Returning wrong string in route
  • Misunderstanding extension setup timing
4. Identify the error in this Flask extension initialization code:
from flask import Flask
from flask_mail import Mail

mail = Mail()

def create_app():
    app = Flask(__name__)
    mail.init_app()
    return app
medium
A. Missing app argument in mail.init_app()
B. Mail extension should be created inside create_app()
C. Flask app instance should be created after mail.init_app()
D. No error, code is correct

Solution

  1. Step 1: Check init_app() usage

    The init_app() method requires the Flask app instance as an argument.
  2. Step 2: Identify missing argument

    In the code, mail.init_app() is called without passing app, causing an error.
  3. Final Answer:

    Missing app argument in mail.init_app() -> Option A
  4. Quick Check:

    init_app() needs app argument [OK]
Hint: Always pass app to init_app() [OK]
Common Mistakes:
  • Calling init_app() without app
  • Creating extension inside factory unnecessarily
  • Confusing order of app and extension creation
5. You want to create a Flask app factory that supports multiple extensions using the extension initialization pattern. Which code snippet correctly initializes two extensions db and login_manager inside the factory?
hard
A. db = SQLAlchemy(app) login_manager = LoginManager(app) def create_app(): app = Flask(__name__) return app
B. db = SQLAlchemy() login_manager = LoginManager() def create_app(): app = Flask(__name__) db.init_app(app) login_manager.init_app(app) return app
C. def create_app(): app = Flask(__name__) db = SQLAlchemy(app) login_manager = LoginManager(app) return app
D. def create_app(): app = Flask(__name__) db = SQLAlchemy() login_manager = LoginManager() db.init_app() login_manager.init_app() return app

Solution

  1. Step 1: Create extensions outside factory

    Extensions should be created once outside the factory without app argument.
  2. Step 2: Initialize extensions inside factory

    Inside create_app(), call init_app(app) on each extension to bind them to the app.
  3. Final Answer:

    db = SQLAlchemy()\nlogin_manager = LoginManager()\ndef create_app():\n app = Flask(__name__)\n db.init_app(app)\n login_manager.init_app(app)\n return app -> Option B
  4. Quick Check:

    Create extensions once, init_app inside factory [OK]
Hint: Create extensions once, call init_app(app) inside factory [OK]
Common Mistakes:
  • Passing app to extension constructor outside factory
  • Calling init_app() without app argument
  • Creating extensions inside factory repeatedly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard