Learn Flask by Examples
Flask 3.0+Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It began as a simple wrapper around Werkzeug and Jinja and has become one of the most popular Python web frameworks.
These examples cover the core concepts of Flask development, from basic routing and request handling to modular application structure with Blueprints. You will learn how to handle various types of client data and construct appropriate responses.
Route Path Matching
Routing is the mechanism that maps URLs to specific functions in your application. Flask provides flexible routing capabilities, including variable rules and type converters.
Request Query Parameters
Query parameters are key-value pairs added to the end of a URL (e.g., ?key=value). They are commonly used for filtering, pagination, and search queries.
Request Form Data
Handling HTML form submissions is a core task for web apps. Flask makes accessing POST data straightforward via the `request.form` object.
Request JSON Payload
Modern single-page applications (SPAs) and mobile apps often communicate via JSON APIs. Flask provides built-in support for parsing JSON request bodies.
Response Object Structure
While you can return strings or dictionaries from views, sometimes you need more control. The Response object allows you to set headers, cookies, and status codes explicitly.
Response Header Configuration
Setting HTTP headers is vital for security, caching, and content negotiation. This demonstrates how to add headers to responses globally using `after_request` hooks.
Blueprint URL Groups
As Flask applications grow, putting all routes in one file becomes unmanageable. Blueprints allow you to organize your application into distinct modules (e.g., auth, admin, api) with their own routes and templates.
Template Inheritance System
Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.
Template Context Data
Passing data from your Python view functions to your HTML templates is the core of dynamic web pages. This demonstrates how to pass variables and access them securely.
Template Loop Blocks
Iterating over lists and dictionaries is a fundamental requirement for displaying dynamic content. Jinja2 provides a robust `for` loop with special helper variables.
Template Conditional Blocks
Conditional logic allows your templates to adapt based on the data. You can show or hide elements, apply different classes, or render entirely different layouts using `if`, `elif`, and `else`.
Static Asset Loading
Web applications need to serve static files like CSS, JavaScript, and images. Flask provides a dedicated `static` folder and the `url_for` function to generate correct URLs for these assets.
Jinja Custom Filters
Filters modify variables before they are rendered (e.g., formatting dates or capitalizing text). Flask allows you to define your own custom filters to handle application-specific formatting logic.
Session Data Storage
Sessions allow you to store information specific to a user from one request to the next. Unlike plain cookies, Flask sessions are cryptographically signed, meaning users can see the data but cannot modify it unless they know the secret key.
Cookie Data Structure
Cookies are small pieces of data stored on the client's browser. Unlike sessions, raw cookies are not signed and can be modified by the user, so they should not be used for sensitive data.
Database Connection Handling
Managing database connections efficiently is critical. Flask provides the `g` object and `teardown_appcontext` hook to manage resources like database connections during a request lifecycle.
SQLAlchemy Model Mapping
Flask-SQLAlchemy is an extension that simplifies using SQLAlchemy with Flask. Models map Python classes to database tables, allowing you to work with objects instead of raw SQL.
SQLAlchemy Relationship Mapping
Defining relationships between tables (One-to-Many, Many-to-Many) is a core feature of SQLAlchemy. It allows you to navigate between related records using simple Python attributes.
WTForms Field Definitions
Flask-WTF integrates WTForms with Flask. Defining forms as classes with typed fields makes handling form data robust, reusable, and secure against CSRF attacks.
WTForms Validation Rules
Validation ensures that the data submitted by users meets your requirements before you process it. WTForms handles this elegantly with the `validate_on_submit()` method.
Error Handler Registration
Handling errors gracefully is essential for a good user experience. This example demonstrates how to register custom error handlers to display friendly pages instead of generic server errors.
Logging Configuration Setup
Proper logging is vital for debugging and monitoring. This sample shows how to configure Flask's built-in logger to output messages to both the console and a file.
Application Configuration Modes
Managing configuration across different environments (Development, Testing, Production) is a common challenge. This example shows how to structure your config using Python classes.
JSON Web Token Structure
JWTs are a popular method for stateless authentication in APIs. This sample demonstrates how to generate and verify tokens using the PyJWT library within a Flask route.
Signal Receiver Hooks
Signals allow you to decouple your application logic by subscribing to events. This example shows how to use the `blinker` library to listen for Flask's built-in signals.

