Bird
Raised Fist0
Flaskframework~20 mins

Application factory pattern in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Flask Factory Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
1:30remaining
What does the Flask app factory function return?
Consider this Flask app factory function:
def create_app():
    app = Flask(__name__)
    @app.route('/')
    def home():
        return 'Hello!'
    return app

What does create_app() return?
Flask
def create_app():
    app = Flask(__name__)
    @app.route('/')
    def home():
        return 'Hello!'
    return app
AA function that returns 'Hello!'
BA Flask application instance ready to run
CNone
DA string 'Hello!'
Attempts:
2 left
💡 Hint
Think about what the variable 'app' is inside the function.
❓ state_output
intermediate
1:30remaining
What is the output when running the app created by the factory?
Given this Flask app factory:
def create_app():
    app = Flask(__name__)
    @app.route('/greet')
    def greet():
        return 'Hi there!'
    return app

app = create_app()
with app.test_client() as client:
    response = client.get('/greet')
    print(response.data.decode())

What will be printed?
Flask
def create_app():
    app = Flask(__name__)
    @app.route('/greet')
    def greet():
        return 'Hi there!'
    return app

app = create_app()
with app.test_client() as client:
    response = client.get('/greet')
    print(response.data.decode())
AHello!
B404 Not Found
CHi there!
DTypeError
Attempts:
2 left
💡 Hint
Check the route defined inside the factory.
❓ lifecycle
advanced
1:30remaining
When is the Flask app instance created in the factory pattern?
In the application factory pattern, when does the Flask app instance get created?
def create_app():
    app = Flask(__name__)
    # setup code
    return app
Flask
def create_app():
    app = Flask(__name__)
    # setup code
    return app
AEach time create_app() is called
BOnly once when the module is imported
CWhen the server starts automatically
DWhen the first request is received
Attempts:
2 left
💡 Hint
Think about what happens inside the function.
📝 Syntax
advanced
1:30remaining
Which option correctly registers a blueprint inside the factory?
You want to register a blueprint inside the Flask app factory. Which code snippet is correct?
from flask import Flask, Blueprint
bp = Blueprint('bp', __name__)
@bp.route('/hello')
def hello():
    return 'Hello Blueprint!'

def create_app():
    app = Flask(__name__)
    # register blueprint here
    return app
Flask
from flask import Flask, Blueprint
bp = Blueprint('bp', __name__)
@bp.route('/hello')
def hello():
    return 'Hello Blueprint!'

def create_app():
    app = Flask(__name__)
    # register blueprint here
    return app
Aregister_blueprint(app, bp)
Bbp.register_blueprint(app)
Capp.blueprint_register(bp)
Dapp.register_blueprint(bp)
Attempts:
2 left
💡 Hint
Check the Flask app method to add blueprints.
🔧 Debug
expert
2:00remaining
Why does this app factory cause a runtime error?
Examine this code:
def create_app():
    app = Flask(__name__)
    @app.route('/count')
    def count():
        return str(counter)
    counter = 0
    return app

What error occurs when accessing '/count' and why?
Flask
def create_app():
    app = Flask(__name__)
    @app.route('/count')
    def count():
        return str(counter)
    counter = 0
    return app
ANameError because 'counter' is used before assignment
BAttributeError because 'counter' is not an attribute
CNo error, returns '0'
DTypeError because 'counter' is not a string
Attempts:
2 left
💡 Hint
The route handler function body executes at request time, after the factory function has fully executed including the assignment.

Practice

(1/5)
1. What is the main purpose of the application factory pattern in Flask?
easy
A. To create the Flask app inside a function for better flexibility and configuration
B. To write all routes directly in the main script without functions
C. To avoid using blueprints in the application
D. To hardcode configuration values in the app instance

Solution

  1. Step 1: Understand the pattern's purpose

    The application factory pattern creates the Flask app inside a function instead of globally. This allows creating multiple app instances with different settings.
  2. Step 2: Compare options to the pattern's goal

    The other options contradict the flexibility and organization benefits of the pattern. Only "To create the Flask app inside a function for better flexibility and configuration" correctly describes the main purpose.
  3. Final Answer:

    To create the Flask app inside a function for better flexibility and configuration -> Option A
  4. Quick Check:

    Application factory = create app in function [OK]
Hint: Remember: factory means create inside a function [OK]
Common Mistakes:
  • Thinking app is created globally, not inside a function
  • Confusing blueprints with the factory pattern
  • Assuming configuration is hardcoded, not flexible
2. Which of the following is the correct way to define an application factory function in Flask?
easy
A. def create_app():\n return Flask
B. app = Flask(__name__)\ndef create_app():\n return app
C. def create_app():\n app = Flask(__name__)\n return app
D. def create_app():\n app = Flask\n return app

Solution

  1. Step 1: Check function definition and app creation

    def create_app():\n app = Flask(__name__)\n return app correctly defines a function named create_app that creates a Flask instance and returns it.
  2. Step 2: Identify syntax errors or incorrect returns

    app = Flask(__name__)\ndef create_app():\n return app creates app outside the function, which is not factory pattern. def create_app():\n return Flask returns the Flask class, not an instance. def create_app():\n app = Flask\n return app tries to assign Flask class without parentheses, causing error.
  3. Final Answer:

    def create_app():\n app = Flask(__name__)\n return app -> Option C
  4. Quick Check:

    Factory function creates and returns app instance [OK]
Hint: Factory returns a new Flask instance inside a function [OK]
Common Mistakes:
  • Returning the Flask class instead of an instance
  • Creating app outside the factory function
  • Missing parentheses when creating Flask instance
3. Given this code snippet using the application factory pattern, what will print(app.config['DEBUG']) output?
def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    return app

app = create_app()
print(app.config['DEBUG'])
medium
A. False
B. True
C. None
D. KeyError

Solution

  1. Step 1: Trace the factory function execution

    The function create_app creates a Flask app and sets app.config['DEBUG'] = True before returning the app.
  2. Step 2: Check the printed config value

    After calling create_app(), the returned app has DEBUG set to True. So printing it outputs True.
  3. Final Answer:

    True -> Option B
  4. Quick Check:

    Config DEBUG set True, print shows True [OK]
Hint: Config set inside factory is available after creation [OK]
Common Mistakes:
  • Assuming default DEBUG is False without setting
  • Expecting KeyError if config key is missing (it's set here)
  • Confusing app instance with factory function
4. Identify the error in this application factory code:
def create_app():
    app = Flask(__name__)
    @app.route('/')
    def home():
        return 'Hello'
    return app

app = create_app()
app.run()
medium
A. Missing parentheses in Flask constructor
B. Calling app.run() outside the factory is incorrect
C. Route decorator used incorrectly inside factory
D. No error; code runs correctly

Solution

  1. Step 1: Review the factory function structure

    The function creates a Flask app, defines a route inside it, and returns the app instance.
  2. Step 2: Check usage of app.run()

    Calling app.run() outside the factory is normal to start the server. The code is valid and will run correctly.
  3. Final Answer:

    No error; code runs correctly -> Option D
  4. Quick Check:

    Defining routes inside factory and running app outside is valid [OK]
Hint: Routes can be inside factory; run app after creation [OK]
Common Mistakes:
  • Thinking app.run() must be inside factory
  • Assuming route decorators can't be inside factory
  • Confusing Flask constructor syntax
5. You want to create a Flask app using the application factory pattern that registers a blueprint and initializes an extension. Which code snippet correctly applies this pattern?
hard
A. def create_app(): app = Flask(__name__) from .views import main_bp app.register_blueprint(main_bp) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() db.init_app(app) return app
B. app = Flask(__name__) from .views import main_bp app.register_blueprint(main_bp) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app)
C. def create_app(): app = Flask(__name__) from .views import main_bp app.register_blueprint(main_bp) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) return app
D. def create_app(): app = Flask(__name__) from .views import main_bp main_bp.register_blueprint(app) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy(app) return app

Solution

  1. Step 1: Understand blueprint registration

    Blueprints are registered on the app using app.register_blueprint(). Two options do this correctly, while one incorrectly calls main_bp.register_blueprint(app).
  2. Step 2: Check extension initialization

    For extensions like SQLAlchemy, the recommended pattern is to instantiate the extension without the 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.
  3. Final Answer:

    def create_app(): app = Flask(__name__) from .views import main_bp app.register_blueprint(main_bp) from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() db.init_app(app) return app -> Option A
  4. Quick Check:

    Blueprint registered on app; extension initialized with init_app [OK]
Hint: Register blueprints on app; init extensions with init_app(app) [OK]
Common Mistakes:
  • Registering blueprint on blueprint instead of app
  • Creating extension with app inside factory instead of init_app
  • Not importing blueprint inside factory function
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