Skip to main content

Overview

Flask is a lightweight WSGI web application framework for Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications by providing a flexible core that doesn't enforce a specific project layout or database choice.

The "Micro" Framework​

Flask is often called a "micro" framework because it keeps its core simple but extensible. It doesn't include a database abstraction layer, form validation, or any other components where pre-existing third-party libraries already provide common solutions. Instead, Flask supports extensions that can add these features to your application as if they were implemented in Flask itself.

Core Concepts​

The Application Object​

The Flask class is the central registry for your application. You create an instance of this class to register routes, configuration, and extensions.

from flask import Flask
app = Flask(__name__)

Routing and Views​

Routes map URL patterns to Python functions (views). Flask uses decorators to handle this mapping cleanly.

@app.route("/user/<name>")
def show_user(name):
return f"Hello, {name}!"

Context Globals​

Flask uses "context locals" (implemented via contextvars) so that you can access request-specific data globally without passing objects between functions.

  • request: The current HTTP request object.
  • session: A dictionary-like object for storing data across requests.
  • g: A temporary storage object for a single request (e.g., a database connection).
  • current_app: A proxy to the application handling the current request.

Blueprints​

For larger applications, Introduction to Blueprints allow you to organize your code into modular components. They record operations to be executed when registered on an application later.

How It Works​

  1. Initialization: You create a Flask instance and configure it.
  2. Registration: You attach view functions to routes using @app.route or app.add_url_rule.
  3. Request Handling: When a request arrives, Flask creates a RequestContext and pushes it to the stack.
  4. Matching: The URL is matched against registered rules using the underlying Flask Framework Ecosystem Context routing system.
  5. Dispatching: The associated view function is called.
  6. Response: The view returns a string, tuple, or Response object, which Flask converts into a valid WSGI response.

Use Cases​

Simple Web Service​

A minimal API that returns JSON data.

from flask import Flask, jsonify

app = Flask(__name__)

@app.get("/api/data")
def get_data():
return jsonify({"status": "success", "value": 42})

Server-Side Rendered App​

Using Jinja Environment and Templates templates to serve HTML.

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
return render_template("index.html", title="Home")

Modular Application​

Using Blueprints to separate admin logic from the frontend.

from flask import Blueprint, Flask

admin_bp = Blueprint("admin", __name__, url_prefix="/admin")

@admin_bp.route("/")
def admin_index():
return "Admin Dashboard"

app = Flask(__name__)
app.register_blueprint(admin_bp)

When to Use Flask​

  • Prototyping: When you need to get a web service up and running in minutes.
  • Microservices: Its small footprint makes it ideal for specialized, single-purpose services.
  • Custom Architectures: When you want full control over which libraries (ORM, Auth, etc.) to use.

When Not to Use Flask​

  • Strict Requirements: If your team requires a "batteries-included" framework with a standard way of doing everything (consider Django).
  • Async-First: While Flask supports async views, it is fundamentally a WSGI (synchronous) framework. For high-concurrency async-native apps, consider Quart or FastAPI.

Integration / Stack Compatibility​

Flask is built on top of several robust libraries:

  • Werkzeug: Handles routing, debugging, and WSGI utilities.
  • Jinja2: The default template engine.
  • Itsdangerous: Handles cryptographically signed data (used for sessions).
  • Click: Powers the flask command-line interface.
  • Blinker: Provides support for signals.

Getting Started Pointers​

FAQ​

Is Flask production-ready? Yes. It is used by major companies like Netflix, Reddit, and Lyft. However, you should use a production WSGI server like Gunicorn or uWSGI instead of the built-in development server.

How do I handle databases? Flask doesn't include an ORM. Most developers use the Flask-SQLAlchemy extension, but you can use any library like Peewee, PonyORM, or even raw SQL drivers.

What is the difference between g and session? g is for data you want to share during a single request (it's wiped after the response). session uses cookies to remember data across multiple requests from the same user.

Can I use Flask for async programming? Yes, Flask supports async def view functions and will manage the event loop for you if asgiref is installed.