liveBook · Manning

Application factory

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

An application factory is a callable that creates and configures an application instance when invoked.

An application factory is a callable that creates and configures an application instance when invoked. In Flask, it replaces direct app creation with a create_app() function, giving the application more control over initialization and making it easier for external modules to use. section 7.3.1

A practical refactoring moves the Flask application into an app package. The package holds templates and static assets, while myblog.py becomes a small entry point that imports create_app() and calls it. section 7.3.1

The pattern supports a gradual move toward clearer application architecture:

  • Keep routes and rendering behavior inside the factory initially, preserving the existing page while changing the structure. section 7.3.1
  • As the application grows, move related routes into a package namespace and register its Blueprint from the factory. section 7.4.2

Minimal factory entry point

from flask import Flask\n\ndef create_app():\n app = Flask(__name__)\n with app.app_context():\n from . import intro\n app.register_blueprint(intro.intro_bp)\n return app

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains package restructuring, factory invocation, route migration, and Blueprint registration, but stops short of broader configuration or testing patterns.
Examples
Uses the MyBlog restructuring, create_app() entry point, package tree, home route, and intro Blueprint as concrete examples.
What it assumes
Assumes familiarity with Flask app creation, Python imports, packages, routes, templates, and static assets.
What you can do after
Build it from scratch by defining create_app(), moving application setup into a package, and registering feature Blueprints.
How it connects
Connects application factories with Python packages, Flask application instances, application contexts, and Blueprints.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.