Learn Flask

Lightweight Python web framework: routing, templates and nothing you don't ask for

22 lessons · 4 hours · 4 levels · covers Flask 3.1

Flask is a small, explicit Python web framework built on Werkzeug (WSGI, routing, request and response objects) and Jinja (templates). You start with a single file and add structure and extensions as the project grows. It is widely used for websites, internal tools and JSON APIs, and its simplicity makes it a great way to learn how web apps really work.

Before you start

Flask builds on these; the tree links to the exact lessons you need.

How deep do you want to go?

1. EssentialsRead and write simple code, do the everyday basics7 lessons · 1 hour in total
2. PracticalUse it productively at work, with the usual idioms14 lessons · 3 hours in total
3. AdvancedThe less common features, performance and trade-offs19 lessons · 4 hours in total
4. ExpertInternals and the edge cases experts know22 lessons · 4 hours in total

The Flask tree

FlaskYour first Flask appYour first Flask appRoutes, URL variables and methodsRoutes, URL variablesand methodsReading the requestReading the requestResponses, status codes and JSONResponses, statuscodes and JSONRendering Jinja templatesRendering Jinjatemplatesurl_for, redirects and static filesurl_for, redirects andstatic filesabort and error handlersabort and errorhandlersSessions and cookiesSessions and cookiesHandling forms with Post/Redirect/GetHandling forms withPost/Redirect/GetConfiguration and secretsConfiguration andsecretsOrganizing with blueprintsOrganizing withblueprintsThe application factoryThe applicationfactoryUsing a database with Flask-SQLAlchemyUsing a databasewith Flask-SQLAlch…Testing with pytest and the test clientTesting with pytestand the test clientDefining functionsDefining functionsVirtual environments and pipVirtual environmentsand pipSELECT: reading dataSELECT: reading dataCreating and altering tablesCreating and alteringtablesTesting with pytest and unittestTesting with pytestand unittestContext managers and withContext managersand withInheritance, super() and compositionInheritance, super()and compositionasync and await with asyncioasync and await withasyncio
Essentials and Practical shown (14 of 22 lessons); the full list is below. Click a lesson to read it.

All 22 lessons, in order

Getting started

  1. Your first Flask app · Essentials · 10 min

    Create a Flask application object, register a view with @app.route and run the development server with debug mode.

  2. Routes, URL variables and methods · Essentials · 12 min

    Capture parts of the URL with converters like <int:id>, restrict HTTP methods, and understand trailing-slash rules.

Requests and responses

  1. Reading the request · Essentials · 12 min

    Use the request object to read query parameters, form fields, JSON bodies, headers, cookies and uploaded files.

  2. Responses, status codes and JSON · Essentials · 10 min

    Return strings, dicts, tuples or Response objects to control the body, status code, headers and content type.

  3. abort and error handlers · Essentials · 8 min

    Stop a request early with abort(404), and render custom pages or JSON for errors with @app.errorhandler.

  4. Sessions and cookies · Practical · 10 min

    Store per-user data across requests in Flask's signed-cookie session, configured with a strong SECRET_KEY.

Templates and forms

  1. Rendering Jinja templates · Essentials · 12 min

    Render HTML from templates/ with render_template, pass variables, and rely on autoescaping and template inheritance.

  2. url_for, redirects and static files · Essentials · 8 min

    Build URLs from endpoint names with url_for, redirect between views and serve CSS, JS and images from static/.

  3. Handling forms with Post/Redirect/Get · Practical · 12 min

    Process HTML form submissions: validate fields, re-render with errors, flash a message and redirect on success.

Structuring an app

  1. Configuration and secrets · Practical · 10 min

    Load settings into app.config from objects, files and FLASK_-prefixed environment variables, keeping secrets out of code.

  2. Organizing with blueprints · Practical · 12 min

    Group related routes, templates and error handlers into blueprints with URL prefixes, and build their URLs with dotted endpoints.

  3. The application factory · Practical · 12 min

    Create the app inside a create_app() function that loads config, initializes extensions and registers blueprints.

  4. Application context, request context and g · Advanced · 12 min

    Understand when current_app, request, session and g are available, and push contexts yourself outside requests.

  5. Request hooks and middleware-like logic · Advanced · 10 min

    Run code around every request with before_request, after_request and teardown_request, and know when each fires.

  6. Class-based views and JSON APIs · Advanced · 12 min

    Use MethodView to map HTTP methods to class methods for REST resources and reuse logic across endpoints.

Data and testing

  1. Using a database with Flask-SQLAlchemy · Practical · 15 min

    Define models with Flask-SQLAlchemy, query with db.select and db.session, and get 404s with get_or_404.

  2. Testing with pytest and the test client · Practical · 12 min

    Write pytest fixtures that build the app with test config, then drive it with the test client and CLI runner.

Security and production

  1. Security essentials · Advanced · 14 min

    Protect a Flask app against XSS, CSRF, session theft and oversized requests with escaping, tokens, cookie flags and limits.

  2. Deploying to production · Advanced · 14 min

    Run Flask under a production WSGI server like Gunicorn behind a reverse proxy, with ProxyFix, logging and static files handled.

Internals

  1. WSGI and Werkzeug under the hood · Expert · 15 min

    See Flask as a WSGI callable built on Werkzeug's routing, request and response objects, and write WSGI middleware.

  2. How request and current_app proxies work · Expert · 12 min

    Learn how Flask's globals are LocalProxy objects over contextvars, and how to use them safely with threads.

  3. Async views and the concurrency model · Expert · 12 min

    Know how Flask handles concurrent requests, what async def views really do, and when to choose Quart or another stack.