liveBook · Manning

Flask application instance

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

A Flask application instance is the runtime Flask object that stores application configuration and routes and runs the web server.

A small web server needs somewhere to connect URLs to Python functions. The Flask application instance fills that role: `app = Flask(__name__)` creates it, and `@app.route("/")` registers a function to answer requests for `/`. section 6.4.2

from flask import Flask      #1
 
app = Flask(__name__)        #2
 
@app.route("/")              #3
def home():                  #4
    return "Hello World!"

This minimal application returns “Hello World!” at the root URL. Running it with `flask run` starts Flask’s request-handling loop; the application does not need to write its own loop. section 6.4.2

Keeping the instance in one large `app.py` file is convenient at first. As features move into separate modules, however, those modules need access to the instance to register endpoints. Importing it back from `app.py` while `app.py` imports the feature modules creates a circular-reference problem. section 7.3 section 7.3.1

For a growing application, make the instance part of a clearer structure:

  • Put the main application code in a Python package, with an `__init__.py` file. section 7.3.1
  • Create the instance inside a `create_app()` factory, where additional functionality can access it. section 7.3.1 section 7.4.4
  • Call the factory from a small entry-point file and retain its returned instance for the application's lifetime. section 7.3.1 section 7.4.4
from app import create_app
 
app = create_app()

The entry point remains short: it imports `create_app()` and assigns the returned instance to `app`. The change is about organizing a growing application, not changing what its page displays. section 7.3.1

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

How deep it goes
Works through instance creation, route registration, and factory-based refactoring; describes Flask’s request loop without implementing it.
Examples
Uses a root route returning “Hello World!” and a refactored blogging application with a `create_app()` entry point.
What it assumes
Assumes familiarity with Python functions and modules; revisits packages before using them to organize the Flask application.
What you can do after
Build it from scratch: create a Flask instance, register a route, then move instance creation into a factory as the application grows.
How it connects
Links the instance to Flask routes, endpoint functions, Python packages, application factories, and circular imports.

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.