Python Flask

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

The reference material consulted while preparing these pages is listed in the section bibliography.

This section is written against Flask 3.1.3 (released 2026-02-18), Werkzeug 3.1.9 and Python 3.13, checked on 2026-10-07. Flask 3.1 supports Python 3.9 and newer, while the examples use Python 3.10+ syntax. Flask 3.2 had not been released on that date, so the changes planned for it (the merge of the application and request contexts, the removal of __version__, a 303 status for redirect, and the end of Python 3.9 and 3.10 support) are described as upcoming wherever they matter, and are collected on What’s Changed & Migration.

What Flask is

Flask is a Python web framework for the WSGI protocol. It is deliberately small: it gives you routing, request and response objects, a template engine, signed cookie sessions, a command-line interface and a test client, and it leaves the choice of database layer, form library, authentication and every other building block to you or to extensions. "Micro" means that the core does not decide those things for you, not that the framework is only for small applications.

Flask is not written from scratch. It is a thin layer over the Pallets libraries, and most of what you use daily is implemented one level down:

  • Werkzeug provides the WSGI toolkit: the Request and Response classes, the URL routing system, the development server and the interactive debugger.

  • Jinja renders the templates.

  • Click implements the flask command and your own CLI commands.

  • ItsDangerous signs the session cookie and other tokens.

  • MarkupSafe provides the escaping behind Jinja’s autoescape.

  • Blinker provides the signals.

This section is for developers who:

  • know Python and want to build server-rendered sites, JSON APIs or both with Flask, from a first route to a deployed, tested and monitored application

  • are coming from Django, FastAPI, Spring Boot, Express or ASP.NET Core and want a precise map of what Flask does itself, what an extension does and what is left to you

  • maintain a Flask application written for Flask 1.x or 2.x, or learned from older tutorials and books, and need the current idioms (DeclarativeBase models, db.session.execute(db.select(...)), flask --app, from_prefixed_env, SECRET_KEY_FALLBACKS) together with a table of what to change

The Bookshelf scenario

Every example builds one small original application, the Bookshelf, so the pages fit together instead of being isolated snippets:

  • books, authors, reviews and users tables, modelled with SQLAlchemy 2.0 and versioned with Flask-Migrate

  • a catalog blueprint (Jinja pages, WTForms forms, message flashing and uploads of cover images), an auth blueprint (Flask-Login), an admin blueprint (Flask-Admin) and an api blueprint (flask-smorest and JWT)

  • English and Spanish pages with Flask-Babel, caching with Flask-Caching, a Celery job that sends a review digest and a live "new reviews" stream over Server-Sent Events

  • tests with pytest, and deployment with Gunicorn behind nginx and in Docker

Diagram of the Bookshelf application. Clients reach nginx, which terminates TLS, serves static files directly and proxies other requests to Gunicorn. Gunicorn runs WSGI workers that call create_app. The Flask application contains the catalog, auth, admin and api blueprints, the Jinja templates and forms layer, and the extensions wired with init_app. The application reads and writes PostgreSQL and uses Redis for cache, sessions, rate limits and as the Celery broker. A Celery worker started from the same application factory takes tasks from the queue.
Figure 1. The Bookshelf application: clients, nginx, Gunicorn, the Flask application with its blueprints and extensions, and its data services

The final project layout (pyproject.toml, src/bookshelf/__init__.py with create_app, config.py, extensions.py, models/, catalog/, auth/, admin/, api/, templates/, static/, migrations/, tests/ and instance/) is assembled on Application Factory & Project Layout.

Version baseline

The versions below were read from PyPI on 2026-10-07. Every page states the versions it was written against, and the extension pages state the extension’s own release.

Library Version Requires Python Role in this section

Flask

3.1.3

3.9+

the framework; 3.2 is unreleased

Werkzeug

3.1.9

3.9+

WSGI toolkit, routing, test client, debugger

Jinja

3.1.6

3.7+

templates

Click

8.5.0

3.10+

command line

ItsDangerous

2.2.0

3.8+

signed cookies and tokens

MarkupSafe

3.0.4

3.9+

escaping

Blinker

1.9.0

3.9+

signals

Quart

0.23.1

3.13+

the ASGI re-implementation of the Flask API

The extension releases current on the same date were Flask-SQLAlchemy 3.1.1, Flask-Migrate 4.1.0, Flask-WTF 1.3.0, Flask-Login 0.6.3, Flask-JWT-Extended 4.7.4, flask-smorest 0.47.0, APIFlask 3.1.2, Flask-Caching 2.5.1, Flask-Babel 4.0.0, Flask-Admin 2.2.1, Celery 5.6.3, Gunicorn 26.2.0 and Waitress 3.0.2. Several of them have not had a release for a long time (Flask-Login, Flask-Babel and Flask-SQLAlchemy among them), which is why the Extensions & Ecosystem page rates the maintenance status of each.

The four books

Four published books were consulted for the concepts a Flask developer meets in practice, and to find the idioms that are out of date today. They are cited, never copied: no text, code listing, figure or data set from any of them appears in this section, every example is written against the current official documentation, and where a book and the documentation disagree the documentation wins.

Book Edition ISBN Publisher page Companion code

Shalabh Aggarwal, Flask Framework Cookbook: Enhance your Flask skills with advanced techniques and build dynamic, responsive web applications

Packt, 3rd edition, June 2023

978-1-80461-110-4

Packt product page

Flask-Framework-Cookbook-Third-Edition

Shalabh Aggarwal, Flask Framework Cookbook: Over 80 proven recipes and techniques for Python web development with Flask

Packt, 2nd edition, July 2019

978-1-78995-129-5

Packt product page

Flask-Framework-Cookbook-Second-Edition

José Haro Peralta, Microservice APIs: Using Python, Flask, FastAPI, OpenAPI and more

Manning, 1st edition, December 2022

978-1-61729-841-7

Manning book page

abunuwas/microservice-apis

Olatunde Adedeji, Full-Stack Flask and React: Learn, code, and deploy powerful web applications with Flask 2 and React 18

Packt, 1st edition, October 2023

978-1-80324-844-8

Packt product page

Full-Stack-Flask-and-React

How each book is used:

  • The two editions of the Flask Framework Cookbook are recipe books that cover the whole ecosystem: configuration, Jinja, SQLAlchemy, WTForms, authentication, REST, administration, internationalization, testing, deployment, containers and miscellaneous tips. The 3rd edition targets Flask 2.2, Werkzeug 2.2, SQLAlchemy 2.0 and Flask-SQLAlchemy 3.0 on Python 3.11, and the 2nd edition targets Flask 1.0, Werkzeug 0.15, SQLAlchemy 1.3 and Flask-SQLAlchemy 2.4 on Python 3.7, so the 2nd edition matters mostly for the Flask 1.x idioms you will meet in old code.

  • Microservice APIs is a framework-agnostic API design book. Only its chapter on Flask uses flask-smorest and marshmallow, and its other chapters on API design, documentation, security and testing are applied to Flask on the API and testing pages of this section.

  • Full-Stack Flask and React is half a React book. Only its Flask chapters are relevant here, on Flask 2.3 with Flask-SQLAlchemy and Flask-JWT-Extended, and the React side is covered by the site’s React section.

The Pallets libraries

Flask is one of the projects of the Pallets organization, together with the libraries it is built on. These are the sources behind the architecture page, and the reason many questions about Flask are really questions about one of them.

Library What it contributes to Flask Documentation

Werkzeug

Request and Response, MultiDict, URL maps and converters, the dev server and reloader, the debugger, the test client, ProxyFix, secure_filename, password hashing helpers

werkzeug.palletsprojects.com

Jinja

the template language, autoescaping, inheritance, macros, filters and tests

jinja.palletsprojects.com

Click

the flask command, @app.cli.command, AppGroup, the CLI test runner

click.palletsprojects.com

ItsDangerous

signing and timestamped serializers for the session cookie and for reset or confirmation tokens

itsdangerous.palletsprojects.com

MarkupSafe

the Markup and escape types used for HTML escaping

markupsafe.palletsprojects.com

Blinker

the signal implementation behind request_started, template_rendered and the other core signals

blinker.readthedocs.io

Extensions and libraries used

Flask extensions are separate packages that follow the init_app pattern. The table lists every extension and library the pages use, by the job it does, and the page that shows it in the Bookshelf.

Area Extensions and libraries Page

Database access

Flask-SQLAlchemy, Flask-SQLAlchemy-Lite, SQLAlchemy 2.0, Python’s sqlite3 module

Flask-SQLAlchemy and SQLite3 and Database Basics

Migrations

Flask-Migrate, Alembic, Flask-Alembic

Database Migrations

Other data stores

redis-py, PyMongo, Flask-MongoEngine, the Elasticsearch Python client

NoSQL, Redis, MongoDB & Search

Forms and CSRF

Flask-WTF, WTForms, wtforms-sqlalchemy

Forms with Flask-WTF

Sessions

Flask-Session, ItsDangerous

Sessions, Cookies & Flashing

Authentication

Flask-Login, Authlib, Flask-Dance, python-ldap, Argon2 and bcrypt

Authentication & Flask-Login and OAuth Social Login & LDAP

Authorization

Flask-Principal, Flask-Security

Authorization & Roles

Security hardening

Flask-Talisman, Flask-Limiter, pip-audit

Security Considerations

API tokens

Flask-JWT-Extended, PyJWT

JWT & API Authentication

API frameworks and schemas

flask-smorest, marshmallow, apispec, APIFlask, Pydantic, Flask-RESTX, flask-openapi3 and Flask-RESTful (the last three for the code you will meet)

Building REST APIs and OpenAPI & API Documentation

Browser integration

Flask-CORS, Vite

Single-Page Apps & CORS

Administration and rich text

Flask-Admin, CKEditor, nh3

Admin Interfaces with Flask-Admin

Internationalization

Flask-Babel, Babel

Internationalization with Flask-Babel

Caching

Flask-Caching, cachelib

Caching

Background jobs and e-mail

Celery, RQ, Flask-Mail

Background Jobs, Celery & Email

Async and real-time

gevent, asgiref, Quart, Hypercorn, Uvicorn, flask-sock, Flask-SocketIO

Async, gevent & Quart and Streaming & Server-Sent Events

Testing

pytest, pytest-mock, factory_boy, coverage.py, Schemathesis, Hypothesis

Testing and API Contract & Property-based Testing

Debugging and observability

Flask-DebugToolbar, Sentry, OpenTelemetry, Prometheus, py-spy

Debugging, Logging & Profiling and Cloud Platforms & Monitoring

Servers and proxies

Gunicorn, Waitress, mod_wsgi, uWSGI, nginx, Apache httpd

Deployment: WSGI Servers & Proxies

Tooling

uv, python-dotenv, Docker

Getting Started and Docker & Kubernetes

LLM APIs

the OpenAI Python SDK

Integrating LLM APIs

Specifications used

The pages rely on these specifications and standards, each linked in the bibliography.

  • PEP 3333 (WSGI) and the ASGI specification, for the two server interfaces

  • RFC 9110 (HTTP semantics) and RFC 9111 (HTTP caching), and RFC 6265 (cookies), for status codes, headers, conditional requests and the session cookie

  • RFC 9457 (Problem Details for HTTP APIs), for error payloads

  • RFC 7519 (JSON Web Token), RFC 8725 and RFC 6750, for token authentication

  • OpenAPI 3.1 and JSON Schema 2020-12, for API descriptions

  • the WHATWG HTML Standard (Server-Sent Events) and the WHATWG Fetch Standard (CORS), for streaming and cross-origin requests

  • the OWASP Cheat Sheet Series, for the security guidance the official security page leaves open

Reading path

The pages are ordered so that each one builds on the previous ones. Read them in this order the first time, then use them as a reference:

  1. Foundations: what Flask is made of, a first running app, the application factory, configuration and the two contexts.

  2. Routing, views and requests: URLs, request data, responses, errors, hooks and blueprints.

  3. Templates, sessions, forms and files: Jinja, static files, signed sessions, Flask-WTF and uploads.

  4. Data: sqlite3 and SQLAlchemy, migrations and the other data stores.

  5. Authentication, authorization and security: Flask-Login, social login, roles and the security checklist.

  6. Building APIs: REST design, OpenAPI with flask-smorest, JWT and single-page applications.

  7. Extensions and ecosystem: the extension model, the CLI, signals, the admin, translations, caching and Celery.

  8. Async, streaming and real-time: async views, gevent, Quart, streaming and Server-Sent Events.

  9. Testing and debugging: pytest, contract tests, logging and profiling.

  10. Production: Gunicorn, nginx, containers and cloud platforms.

  11. Beyond the basics: calling LLM APIs, and what changed between releases.

If you already know an older Flask, start with What’s Changed & Migration and read the topic pages afterwards. The cheat sheet at Flask Cheat Sheet condenses the whole section onto one page for quick lookup.

mindmap root((Python Flask)) Foundations Architecture and the Pallets stack Getting started Application factory Configuration Contexts and lifecycle Routing, views and requests Routing and url_for Request data Responses and JSON Errors and hooks Class-based views Blueprints Templates, sessions, forms and files Jinja templates Static files Sessions and flashing Flask-WTF forms File uploads Data sqlite3 basics Flask-SQLAlchemy Migrations Redis, MongoDB and search Authentication, authorization and security Flask-Login OAuth and LDAP Roles Security considerations Building APIs REST design flask-smorest and OpenAPI JWT SPAs and CORS Extensions and ecosystem Extension model CLI and shell Signals Flask-Admin Flask-Babel Caching Celery and e-mail Async, streaming and real-time async, gevent and Quart Streaming and SSE Testing and debugging pytest Contract testing Logging and profiling Production Gunicorn, nginx and ProxyFix Docker and Kubernetes Cloud and monitoring Beyond the basics LLM APIs Changes and migration
Figure 2. The section at a glance

The Flask pages link to existing material instead of repeating it, and cover only what Flask adds.

Topic Where it lives How the Flask section relates

The Python language, typing, asyncio, virtual environments, pytest

Python Reference, including Concurrency & Async, Virtual Environments & Packaging and Testing

Flask pages link here for general Python and cover only what Flask adds.

Other Python web frameworks

Python FastAPI, Django, Python Tornado and Python Pyramid

The introduction compares Flask with each of them, and the migration page covers Flask to FastAPI and Quart.

Mounting Flask inside FastAPI

Sub-applications, WSGI & GraphQL

The migration page links there for WSGIMiddleware instead of repeating it.

OAuth 2.0, OpenID Connect and JWT theory

OAuth Reference

The authentication pages cover only the Flask libraries (Authlib, Flask-Dance, Flask-JWT-Extended).

GraphQL

GraphQL Reference

The REST API page compares GraphQL briefly and links here.

Docker and containers

Docker

The Docker page shows only the Flask-specific Dockerfile and Compose files.

Kubernetes

Kubernetes Reference

The Docker & Kubernetes page shows only the Flask-specific Deployment, probes and migration Job.

Cloud deployment

Cloud

The cloud page covers the Flask-specific parts of each hosting platform.

Database engines

SQL Reference, MongoDB Reference, Redis Reference and Elasticsearch Reference

The data pages cover only how to use each from Flask (clients created in the factory, sessions per request).

Architecture

Architecture, Architectural Patterns and Starting a New Project: Which Path and Which Technologies

The project-layout page links the patterns (hexagonal, repository and service layer).

Messaging and scheduling

Messaging Reference and Scheduling

The Celery page points here for brokers and for schedulers beyond Celery beat.

Image and media processing

Media Optimization

The file-upload page hands the processing of uploaded images over to it.

CORS and front ends

CORS and React

The single-page-application page covers only the Flask side.

AI frameworks and models

AI

The LLM page stays introductory and points here for depth.

Bibliography

Every source used to prepare this section is listed here, each linked to its official site. Individual pages list the subset they derive from under their own == References heading.

Books

Official Flask documentation

Published at flask.palletsprojects.com, grouped as the documentation is (the development version is at flask.palletsprojects.com/en/latest, and the release notes for the unreleased 3.2 are on its changes page):

Flask extensions and companion projects

Libraries and tools used by the pages

Servers, infrastructure and platforms

Specifications and standards

Security guidance

The books are consulted references for the narrative and structure of some topics and for the list of outdated idioms; they are not reproduced here. The official documentation linked above is authoritative, and where the two differ, the documentation of the version you run prevails.