Flask

On this page 7

Flask is a lightweight Python web framework, often called a microframework, that maps URLs to Python functions, handles HTTP requests and responses, and renders templates while leaving database access, form validation and authentication to extensions chosen by the developer. In web architecture, Flask usually sits on the backend as an application layer behind a production web server, serving HTML pages, JSON APIs or both.

Flask is built on two core libraries maintained by the Pallets project: Werkzeug, a toolkit for the WSGI interface between web servers and Python applications, and Jinja, a template engine. Its design philosophy is to keep the core small and explicit, so that a working application can fit in a single file and grow into a structured codebase without changing frameworks.

How Flask processes a request

Flask handles each request by passing it through a WSGI server, matching the URL against registered routes and calling the associated view function, whose return value becomes the HTTP response. The developer declares routes with the @app.route() decorator, and Werkzeug compiles them into a URL map that also supports variable segments such as /users/<int:id>.

During a request, Flask exposes data through context-local objects. The request object holds headers, query parameters and the body, while g stores per-request values such as a database connection. These objects are bound to the current worker thread or greenlet by the application context and request context, which allows code to read request.args without passing the request explicitly through every function.

The following table lists the main stages of the request lifecycle and the hooks Flask offers at each stage.

StageWhat happensDeveloper hook
Context pushApplication and request contexts become activeapp.app_context()
PreprocessingCode runs before the view functionbefore_request
DispatchURL map selects and calls the view@app.route()
Response buildingReturn value becomes a response objectmake_response()
PostprocessingHeaders or cookies are adjustedafter_request
TeardownResources are released, even after errorsteardown_request
Stages of the Flask request lifecycle

Core components and the extension model

The Flask core deliberately ships only routing, templating, sessions and a development server, and every other capability comes from extensions or plain Python libraries. This minimalism is the defining trait of Flask: the framework makes few decisions about the data layer, which gives teams freedom but also places architectural responsibility on them.

Larger applications are organized with blueprints, which group routes, templates and static files into reusable modules, and with the application factory pattern, a function such as create_app() that builds and configures the app instance. The factory pattern makes it possible to create separate instances for testing, development and production with different configuration objects.

The table below shows the components most Flask projects combine, separating built-in features from common extensions.

CapabilitySourceTypical choice
Routing and viewsBuilt inWerkzeug URL map
TemplatingBuilt inJinja with autoescaping
SessionsBuilt inSigned cookie session
Database accessExtensionFlask-SQLAlchemy
Schema migrationsExtensionFlask-Migrate with Alembic
Forms and CSRFExtensionFlask-WTF
User loginExtensionFlask-Login
Cross-origin requestsExtensionFlask-CORS
Built-in features and common extensions

The default session stores data in a cryptographically signed cookie, not on the server. The signature, based on the SECRET_KEY, prevents tampering but does not encrypt the content, so sensitive data should never be placed in the default session.

Flask compared with other web frameworks

Flask is best understood as the unopinionated end of the Python framework spectrum, in contrast to full-stack frameworks that prescribe a database layer, an admin interface and a project layout. Django, for example, includes an ORM, migrations, authentication and an admin site out of the box, while Flask expects the developer to assemble those parts.

The comparison below places Flask next to related frameworks from the same Topic and from the wider Python ecosystem.

FrameworkLanguagePhilosophyInterface
FlaskPythonMinimal core, extensionsWSGI, async views since 2.0
DjangoPythonBatteries includedWSGI and ASGI
FastAPIPythonType-driven APIsASGI
Express.jsJavaScriptMinimal middleware chainNode.js HTTP server
Ruby on RailsRubyConvention over configurationRack
LaravelPHPFull-stack conventionsPHP-FPM or similar
Flask and related web frameworks

Flask is often compared to Express.js, because both expose a small routing core and rely on middleware or extensions for everything else. A key difference is the concurrency model: Flask runs on synchronous WSGI workers by default, so each worker handles one request at a time, whereas Node.js uses an event loop. Flask 2.0 added async def views, but on WSGI they still occupy a worker for the full request; projects that need high-concurrency async I/O often choose an ASGI framework such as Quart, which mirrors the Flask API.

Deploying Flask in production

A production Flask deployment runs the application under a dedicated WSGI server such as Gunicorn, uWSGI or Waitress, typically behind a reverse proxy such as Nginx that terminates TLS and serves static assets. The built-in flask run server is intended only for development, because it is not designed for performance, security hardening or process management.

Configuration should follow the principles of the twelve-factor app: secrets and database URLs come from environment variables, the same build runs in every environment, and logs go to standard output. Containerized deployments commonly run several Gunicorn workers per container, with the worker count often set to about two to four times the CPU cores and then tuned by load testing.

The decision table below summarizes when Flask is a strong fit and when another option is usually better.

SituationRecommendationReason
Small JSON API or microserviceFlask is a strong fitLittle boilerplate, fast start
Machine learning model endpointFlask is a common fitPython ecosystem, simple routes
Content-heavy site with adminPrefer DjangoAdmin and ORM included
Thousands of open connectionsPrefer an ASGI frameworkAsync I/O scales better
Team without strong conventionsFlask with a project templateAvoids inconsistent structure
When to choose Flask

Limitations and common mistakes with Flask

The main risk of Flask is that freedom becomes inconsistency: without agreed conventions, each module may handle database sessions, errors and validation differently. Experienced teams counter this with an application factory, blueprints, a fixed extension set and explicit coding standards from the first sprint.

  • Running debug mode in production exposes the interactive Werkzeug debugger, which allows arbitrary code execution.
  • A weak or committed SECRET_KEY lets attackers forge session cookies.
  • Global mutable state in module variables breaks when several workers or threads serve requests.
  • Blocking calls inside views, such as slow external APIs, exhaust worker capacity; move them to a task queue such as Celery or RQ.
  • Disabling Jinja autoescaping or marking user input as safe reopens cross-site scripting holes.

Understanding it simply

Flask is a small toolkit for building websites and web services in the Python programming language. When a browser asks for a page, Flask decides which piece of code should answer and sends the result back.

Think of it as a well-made kitchen with only the essential tools. It has a stove and a few good knives, and the cook brings any extra appliances needed for a particular menu. That makes Flask quick to start and easy to understand, but the team must choose and organize the extra tools carefully as the project grows.

Applied in practice

A data science team at a regional logistics company has trained a model that predicts delivery delays. To let the dispatch system use it, the team writes a Flask application with a single blueprint and two routes: /health for monitoring and /predict, which accepts a JSON body with route, weather and load data and returns a delay estimate in minutes.

The model is loaded once when the application factory runs, not on every request. The service runs in a container under Gunicorn with four workers behind Nginx, and the secret key and model path come from environment variables. Under typical load the endpoint answers in roughly 40 to 80 milliseconds.

Within two weeks the dispatch software is calling the service in production. The outcome is a small, maintainable prediction API that the data scientists can update themselves, without adopting a full-stack framework they do not need.