Bird
Raised Fist0
Flaskframework~10 mins

Application factory pattern preview in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Application factory pattern preview
Define create_app() function
↓
Inside create_app: Create Flask app instance
↓
Configure app settings
↓
Register blueprints and extensions
↓
Return app instance
↓
Call create_app() to get app
↓
Run app
This flow shows how the application factory function creates and configures the Flask app, then returns it for running.
Execution Sample
Flask
from flask import Flask

def create_app():
    app = Flask(__name__)
    app.config['DEBUG'] = True
    @app.route('/')
    def home():
        return 'Hello, Flask!'
    return app
Defines a function that creates and configures a Flask app, then returns it.
Execution Table
StepActionEvaluationResult
1Call create_app()Function startsEnter create_app function
2Create Flask app instanceapp = Flask(__name__)app object created
3Set config DEBUG=Trueapp.config['DEBUG'] = Trueapp config updated
4Define route '/'@app.route('/')Route registered
5Define home() functiondef home(): return 'Hello, Flask!'Route handler ready
6Return appreturn appapp instance returned
7Assign app = create_app()app = create_app()app variable holds Flask app
8Run appapp.run()Flask server starts
9ExitApp running, waiting for requestsExecution stops here until interrupted
💡 Execution stops after app.run() starts the server and waits for requests.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6After Step 7
appundefinedFlask app instanceConfig DEBUG=True setReturned from create_appAssigned to app variable
Key Moments - 2 Insights
Why do we define the app inside a function instead of globally?
Defining app inside create_app delays creation until called, allowing flexible configuration and testing. See execution_table steps 1-6.
What happens if we call app.run() outside create_app?
app.run() starts the server and blocks further code. It is called after create_app returns the app, as shown in steps 7-8.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the state of 'app' after step 3?
AUndefined
BFlask app instance with DEBUG=True in config
CFunction create_app itself
DRoute '/' registered
💡 Hint
Check variable_tracker column 'After Step 3' and execution_table step 3
At which step is the route '/' registered?
AStep 2
BStep 6
CStep 4
DStep 8
💡 Hint
Look at execution_table step descriptions for route registration
If we did not return 'app' from create_app, what would happen at step 7?
Aapp variable would be None or undefined
Bapp would be a Flask instance anyway
Capp.run() would start normally
DThe server would start twice
💡 Hint
Refer to execution_table step 6 and 7 about returning and assigning app
Concept Snapshot
Application Factory Pattern in Flask:
- Define a function create_app() that creates and configures the app.
- Inside, create Flask instance, set config, register routes.
- Return the app instance.
- Call create_app() to get the app and run it.
- Enables flexible app setup and testing.
Full Transcript
The Application Factory Pattern in Flask means we write a function called create_app that builds and configures the Flask app. When we call this function, it creates the app instance, sets configuration like DEBUG mode, registers routes such as '/' with their handlers, and then returns the app. After that, we assign the returned app to a variable and run it. This pattern helps us create the app only when needed, making it easier to configure differently for testing or production. The execution steps show calling create_app, creating the app, setting config, registering routes, returning the app, assigning it, and running the server. Variables like 'app' change from undefined to a Flask instance with config set. Key points include why the app is created inside a function and when the server starts running.

Practice

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

Solution

  1. Step 1: Understand the pattern's purpose

    The application factory pattern creates the Flask app inside a function instead of a global variable.
  2. Step 2: Benefits of this approach

    This allows flexible configuration, easier testing, and clean registration of extensions and blueprints.
  3. Final Answer:

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

    Application factory = create app in function [OK]
Hint: Remember: factory means 'make inside a function' [OK]
Common Mistakes:
  • Thinking app is created globally
  • Confusing with blueprint usage
  • Assuming it auto-generates templates
2. Which of the following is the correct way to define an application factory function in Flask?
easy
A. def create_app():\n app = Flask\n return app
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 return Flask

Solution

  1. Step 1: Check function definition and app creation

    The factory function must create a Flask instance inside it using Flask(__name__)
  2. Step 2: Verify return of the app instance

    The function should return the created app instance, not the class or a global variable.
  3. Final Answer:

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

    Factory returns new Flask instance [OK]
Hint: Create and return app inside function with Flask(__name__) [OK]
Common Mistakes:
  • Returning Flask class instead of instance
  • Using global app outside function
  • Not calling Flask with parentheses
3. Given this code snippet, 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. True
B. False
C. None
D. KeyError

Solution

  1. Step 1: Analyze config setting inside factory

    The factory sets app.config['DEBUG'] = True before returning the app.
  2. Step 2: Check printed value after app creation

    After calling create_app(), app.config['DEBUG'] is True, so printing it outputs True.
  3. Final Answer:

    True -> Option A
  4. Quick Check:

    Config set to True inside factory [OK]
Hint: Config set inside factory is available after app creation [OK]
Common Mistakes:
  • Assuming default DEBUG is False
  • Expecting KeyError for missing key
  • Confusing config with environment variables
4. Identify the error in this application factory code:
def create_app():
    app = Flask(__name__)
    app.register_blueprint(main)
    return app

app = create_app()

Assume main is a blueprint imported correctly.
medium
A. No error, code is correct
B. Missing app context push before registering blueprint
C. Blueprint must be registered before app creation
D. Blueprint registration should happen inside a separate function

Solution

  1. Step 1: Check blueprint registration timing

    Blueprints are registered on the app instance inside the factory function, which is correct.
  2. Step 2: Verify app context and function structure

    No app context push is needed for registration; the code is valid and follows the pattern.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    Blueprint registered inside factory is valid [OK]
Hint: Register blueprints inside factory before returning app [OK]
Common Mistakes:
  • Thinking app context is needed for registration
  • Trying to register blueprint before app exists
  • Separating registration unnecessarily
5. You want to add a Flask extension (e.g., Flask-Migrate) using the application factory pattern. Which approach is correct?
hard
A. Create the extension instance inside the factory function only
B. Initialize the extension globally, then call init_app(app) inside the factory
C. Initialize the extension after app creation outside the factory
D. Pass the app instance as a parameter to the extension constructor inside the factory

Solution

  1. Step 1: Understand extension initialization pattern

    Extensions are usually created globally without app, then initialized with app inside the factory using init_app(app).
  2. Step 2: Why not create inside factory?

    Creating inside factory loses global access; initializing outside factory after app creation breaks pattern.
  3. Final Answer:

    Initialize the extension globally, then call init_app(app) inside the factory -> Option B
  4. Quick Check:

    Global extension + init_app(app) inside factory [OK]
Hint: Create extension globally, init inside factory [OK]
Common Mistakes:
  • Creating extension instance inside factory only
  • Initializing extension outside factory after app creation
  • Passing app to extension constructor inside factory
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