The Flask App Factory
An app factory is a function that builds the app. Calling it makes a fresh app each time.
Import Flask
The factory needs Flask only. The function below builds the app.
from flask import FlaskWrite the factory
The factory makes the app, adds one route, and returns the app.
def create_app():
app = Flask(__name__)
@app.route("/")
def home():
return "Factory app"
return appBuild an app and ask it
The call builds a fresh app. Its test client asks for / and prints the page.
print(create_app().test_client().get("/").data.decode())Example
from flask import Flask
def create_app():
app = Flask(__name__)
@app.route("/")
def home():
return "Factory app"
return app
print(create_app().test_client().get("/").data.decode())Key points
- def create_app(): builds the app and returns it.
- The routes live inside the factory function.
- Call create_app() to get an app to test or run.
- One factory serves tests and the real server alike.
In this example, create_app makes a fresh app with one route and returns it. The last line calls the factory, asks its test client for /, and prints the page.
Note
The factory returns the app, so callers keep it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does create_app() return?