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 the essentials of web development without enforcing a rigid project structure.
The "Micro" Framework
Web development often forces a choice between "batteries-included" frameworks that make many decisions for you, and low-level libraries that require manual assembly. Flask solves this by being a "micro" framework: it provides a solid core for routing, request handling, and templating, while leaving choices like database integration, form validation, and authentication to the developer or community-provided extensions.
Core Concepts
- The Application Object: An instance of the
Flaskclass acts as the central registry for your application, holding configurations, route definitions, and extension state. - Routing: Flask uses decorators like
@app.route()to map URLs to Python functions (view functions). It supports dynamic URL segments and multiple HTTP methods. - Context Locals: Flask uses "proxies" like
request,session, andgto provide access to data specific to the current request without passing objects between every function. - Blueprints: For larger applications,
Blueprintobjects allow you to modularize your code into distinct components (e.g.,auth,admin,api) that can be registered on the main app. - Templating: Flask integrates the Jinja2 engine, allowing you to generate dynamic HTML with a powerful, designer-friendly syntax.
How It Works
Flask is built on top of two primary libraries: Werkzeug (which handles WSGI, routing, and debugging) and Jinja2 (which handles templating).
- Request Arrival: When a request hits the server, Werkzeug matches the URL against the registered rules.
- Context Setup: Flask creates a request context and pushes it, making the
requestandsessionproxies available. - Dispatching: The matched view function is called.
- Response Generation: The view function returns a string, a tuple, or a
Responseobject. Flask ensures this is converted into a valid WSGI response. - Cleanup: After the response is sent, the context is popped, and teardown functions (like closing database connections) are executed.
Use Cases
Simple Web Service
Create a functional web server in just a few lines of code.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello, Flask!"
JSON API
Flask makes it easy to build RESTful APIs using the jsonify helper.
from flask import Flask, jsonify
app = Flask(__name__)
@app.get("/api/data")
def get_data():
return jsonify({"status": "success", "items": [1, 2, 3]})
Modular Applications
Use Blueprints to organize large codebases.
# auth.py
from flask import Blueprint
auth_bp = Blueprint("auth", __name__, url_prefix="/auth")
@auth_bp.route("/login")
def login():
return "Login Page"
# app.py
from flask import Flask
from .auth import auth_bp
app = Flask(__name__)
app.register_blueprint(auth_bp)
When to Use Flask
- Use Flask when you want full control over your stack, are building a microservice, or need a lightweight framework that doesn't get in your way. It is excellent for learning web development fundamentals.
- When not to use Flask: If you are building a standard CRUD-heavy enterprise application and want everything (ORM, Admin panel, Auth) pre-configured out of the box, a framework like Django might save you time.
Integration & Stack Compatibility
- Python: Requires Python >= 3.10.
- WSGI: Compatible with any WSGI server (Gunicorn, uWSGI, Waitress).
- Async: Supports
asyncview functions when the[async]extra is installed. - Extensions: Works with hundreds of community extensions for SQLAlchemy, WTForms, Marshmallow, and more.
Getting Started Pointers
- Define your first route using the
@app.routedecorator. - Access incoming data via the
flask.requestobject. - Organize growing apps using
flask.Blueprint. - Run your app for development using the
flask runCLI command.
FAQ
- Is Flask "too small" for production? No. Flask powers some of the largest sites in the world (like Pinterest and LinkedIn). Its "micro" nature refers to the core, not its capability.
- How do I handle databases? Flask doesn't include an ORM. Most developers use the Flask-SQLAlchemy extension to integrate with databases.
- Does it support Async? Yes, Flask supports
async defview functions and can be run with an ASGI server using a wrapper or natively in certain configurations. - What are Context Locals? They are objects that look like globals but are actually local to a specific thread or greenlet, ensuring that one user's request data doesn't leak into another's.