Lesson 47 of 59Other frameworks
Flask Essentials
Write a minimal Flask app, handle requests and responses, structure it with an app factory and blueprints, and add extensions.
Flask is the small framework. It gives you routing, a request object, responses, templates and a test client, and stops there. No ORM, no admin, no validation layer. You add exactly what you need through extensions. That makes Flask quick to learn, easy to read, and still very common in production: internal services, dashboards, ML model servers and countless older APIs run on it. Many FastAPI ideas, such as the route decorator, came from Flask, so knowing it makes you comfortable in both worlds.
A minimal app
uv init hello-flask && cd hello-flaskuv add flaskfrom flask import Flask
app = Flask(__name__)
@app.get("/")
def index():
return {"message": "hello"}
@app.get("/hello/<name>")
def hello(name: str):
return f"<p>Hello, {name}!</p>"uv run flask --app app run --debugFlask(__name__) creates the application; the name helps Flask find templates and static files next to your module. @app.get and @app.post are shortcuts for @app.route("/", methods=["GET"]). --debug turns on auto-reload and the interactive debugger. Never enable it in production, because the debugger can run arbitrary code.
Return values are flexible. A string becomes an HTML response, a dict or list becomes JSON, and a tuple adds a status code or headers: return {"error": "not found"}, 404.
Notice one Flask quirk: the returned string interpolates name straight into HTML. That is fine for a demo, but in a real app use templates (Jinja2 escapes variables for you) or markupsafe.escape.
How the route decorator works
The decorator does not change your function. It records it in a table that maps a URL rule and method to a function. When a request comes in, Flask looks up the path, extracts variables, and calls the function. Here is a toy version in plain Python:
Press Run (⌘ Enter) to see what happens.Real Flask uses Werkzeug's router, which also supports converters like <int:post_id>, building URLs from names with url_for, and more, but the shape is the same.
Using the toy router above, what does this print?
print(app.dispatch("DELETE", "/"))Request and response
Flask exposes the current request as a global-looking request object. It is actually a context local: each request, even when many run at once in different threads, sees its own data.
from flask import Flask, abort, jsonify, request
app = Flask(__name__)
TODOS: dict[int, dict] = {}
@app.get("/todos")
def list_todos():
limit = request.args.get("limit", default=20, type=int)
return list(TODOS.values())[:limit]
@app.post("/todos")
def create_todo():
data = request.get_json(silent=True) or {}
title = data.get("title", "").strip()
if not title:
return {"error": "title is required"}, 400
todo_id = len(TODOS) + 1
TODOS[todo_id] = {"id": todo_id, "title": title, "done": False}
return TODOS[todo_id], 201
@app.get("/todos/<int:todo_id>")
def get_todo(todo_id: int):
todo = TODOS.get(todo_id)
if todo is None:
abort(404)
return jsonify(todo)| You want | Flask gives you |
|---|---|
| Query string | request.args |
| JSON body | request.get_json() |
| Form fields | request.form |
| Uploaded files | request.files |
| Headers | request.headers |
| Stop with an error | abort(404) |
Compare this with FastAPI. There is no automatic validation, no typed body and no generated docs. You check title by hand. Teams add Pydantic or marshmallow to validate bodies, or an extension that generates OpenAPI. That is the core Flask trade: less built in, more choice.
{"id": 1}, 201. What does the client receive?The app factory
A module-level app = Flask(__name__) is fine for a single file. It gets awkward fast: tests cannot create an app with different settings, and extensions end up imported everywhere. The standard fix is an app factory, a function that builds and returns a configured app.
from flask import Flask
from .extensions import db
def create_app(config: dict | None = None) -> Flask:
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY="dev",
SQLALCHEMY_DATABASE_URI="sqlite:///app.db",
)
app.config.from_prefixed_env() # FLASK_SECRET_KEY etc. from the environment
if config:
app.config.update(config)
db.init_app(app)
from .todos import bp as todos_bp
app.register_blueprint(todos_bp, url_prefix="/todos")
return appuv run flask --app myapp run --debugFlask finds create_app in the package on its own. In tests you call create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite://"}) to get an isolated app with an in-memory database, then use app.test_client() to send requests.
Inside a request, code that needs the app uses current_app rather than importing a global app, which is what keeps the factory pattern working.
Blueprints
A blueprint is a group of routes, templates and error handlers that you register on an app. It is Flask's version of FastAPI's APIRouter or a Django app.
from flask import Blueprint, request
from .extensions import db
from .models import Todo
bp = Blueprint("todos", __name__)
@bp.get("/")
def list_todos():
todos = db.session.scalars(db.select(Todo).order_by(Todo.id)).all()
return [{"id": t.id, "title": t.title, "done": t.done} for t in todos]
@bp.post("/")
def create_todo():
data = request.get_json(silent=True) or {}
todo = Todo(title=data["title"])
db.session.add(todo)
db.session.commit()
return {"id": todo.id, "title": todo.title, "done": todo.done}, 201Registered with url_prefix="/todos", these routes answer at /todos/. The endpoint names become todos.list_todos, so url_for("todos.list_todos") builds the link.
- hello-flask/
- pyproject.toml
- myapp/
- __init__.pycreate_app()
- extensions.pydb = SQLAlchemy(...)
- models.pyTodo, User
- todos.pyblueprint: /todos
- auth.pyblueprint: /auth
- templates/
- base.html
- tests/
- conftest.pyapp and client fixtures
- test_todos.py
Order what happens when create_app() runs.
- Tap the steps below in the right order.
Extensions
Extensions add the pieces Flask leaves out. They follow the same pattern: create the object once in extensions.py, then call init_app(app) inside the factory.
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import DeclarativeBase
class Base(DeclarativeBase):
pass
db = SQLAlchemy(model_class=Base)Flask-SQLAlchemy wires SQLAlchemy into the app, with a session scoped to each request, and models written in the same 2.0 style as the rest of this course. Other common ones: Flask-Migrate (Alembic for Flask), Flask-Login (sessions for logged-in users), Flask-WTF (forms with CSRF), and Flask-CORS.
Match each Flask concept to its closest equivalent elsewhere in the course.
Sessions and per-request state
Flask's built-in session is a dict stored in a cookie. Flask signs it with SECRET_KEY, so the client can read it but cannot change it without the signature failing. That makes it fine for a user id or a flash message, and wrong for secrets or large data, since everything travels in the cookie on every request. If SECRET_KEY leaks, anyone can forge sessions, so load it from the environment and never commit it.
from flask import session
session["user_id"] = user.id # after a successful login
user_id = session.get("user_id") # on later requests
session.clear() # on logoutFor data that only lives during one request, such as the loaded current user or a database connection, Flask provides g, another context local. A @app.before_request function can load the user into g.user, and every view in that request can read it. It is the closest Flask has to a FastAPI dependency, though without the per-route declarations or the test overrides: you fake it in tests by setting the session through the test client instead.
Templates, errors and tests
Flask uses Jinja2 templates from a templates/ folder. render_template("todos.html", todos=todos) fills one in, and Jinja escapes variables by default, just like Django's templates. Template inheritance ({% extends "base.html" %} with {% block content %}) keeps the layout in one file.
Error handlers turn exceptions into responses. For a JSON API, you usually want every error as JSON, not Flask's default HTML page:
from flask import Blueprint
from werkzeug.exceptions import HTTPException
bp = Blueprint("errors", __name__)
@bp.app_errorhandler(HTTPException)
def handle_http_error(error: HTTPException):
return {"error": error.name, "detail": error.description}, error.codeapp_errorhandler on a blueprint registers the handler for the whole app, so once you register this blueprint in create_app, abort(404) anywhere returns JSON.
Testing uses the factory. A pytest fixture builds a fresh app per test, and the test client sends requests without a running server:
import pytest
from myapp import create_app
from myapp.extensions import db
@pytest.fixture
def client():
app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite://"})
with app.app_context():
db.create_all()
return app.test_client()def test_create_todo(client):
response = client.post("/todos/", json={"title": "Write tests"})
assert response.status_code == 201
assert response.get_json()["title"] == "Write tests"app.app_context() is needed for anything that touches current_app or the database outside a request, such as creating tables or running a one-off script.
Running in production
The flask run server is for development only. In production, run Flask under a WSGI server such as Gunicorn, pointing at the factory:
uv add gunicornuv run gunicorn "myapp:create_app()" --workers 4 --bind 0.0.0.0:8000Flask is a WSGI framework. It supports async def views, but each request still occupies a worker while it runs, so it does not give you the high-concurrency benefits of an ASGI framework like FastAPI. For lots of slow I/O at once, FastAPI is the better fit.
When Flask fits
Flask fits small and medium services where you want full control and a short learning curve: an internal tool, a webhook receiver, a thin service in front of an ML model, a server-rendered site with a few pages. It is also a good choice when a team already knows it well. It fits less well for a large API where you would rebuild FastAPI's validation and docs by hand, or a data-heavy product where you would rebuild Django's admin and auth.
If you inherit a Flask codebase, read create_app first. It tells you the config sources, every extension in use and every blueprint, which together are a map of the whole app. Then open the blueprints one at a time, the same way you would read the routers in a FastAPI project.
- Flask
- A small WSGI web framework: routing, requests, responses and templates, extended with plugins.
- app factory
- A
create_app()function that builds and configures a Flask app on demand. - blueprint
- A group of routes and handlers registered on an app, often with a URL prefix.
- context local
- An object like
requestthat looks global but holds per-request data. - extension
- A Flask plugin such as Flask-SQLAlchemy, set up once and attached with
init_app(app). - WSGI
- The synchronous Python standard interface between web servers and apps, used by Flask and Django.