Why Flask?
Lightweight
Flask is a micro-framework that provides the essentials without imposing a specific structure or dependencies.
Easy to Learn
With its simple and intuitive API, Flask is perfect for beginners and experienced developers alike.
Extensible
Start small and add only what you need with Flask's extensive ecosystem of extensions.
Flask Overview
Flask is a Python micro-framework for web development. Unlike comprehensive frameworks like Django, Flask provides the bare essentials with the flexibility to choose your components and structure your application as you see fit.
When a request comes to a Flask application:
- Flask matches the URL to a registered route
- The corresponding view function is executed
- The view function processes data and may render a template
- A response is returned to the client
Getting Started with Flask
Prerequisites
Before you start, make sure you have:
- Python 3.6 or newer installed
- Basic knowledge of Python programming
- Understanding of basic web concepts (HTTP, HTML)
- A text editor or IDE (VS Code, PyCharm, etc.)
Installation
The recommended way to install Flask is using pip, the Python package manager, within a virtual environment:
Your First Flask Application
Let's create a simple "Hello, World!" application:
Save this code in a file named app.py
and run it:
You should now be able to visit http://127.0.0.1:5000/
in your browser and see "Hello, World!"
Understanding the Code
Flask(__name__)
creates a Flask application instance. The__name__
parameter helps Flask locate resources.@app.route('/')
is a decorator that tells Flask which URL should trigger our function.hello_world()
is a view function that returns content to be displayed in the browser.app.run(debug=True)
starts the development server with debug mode enabled.
Routing and URL Handling
Basic Routing
Routes in Flask are defined using the @app.route
decorator:
Dynamic Routes
You can capture parts of the URL as variables:
Flask supports these converter types:
string
(default): accepts any text without a slashint
: accepts positive integersfloat
: accepts positive floating point valuespath
: like string but also accepts slashesuuid
: accepts UUID strings
HTTP Methods
By default, routes only respond to GET requests. You can specify which HTTP methods are allowed:
URL Building
Flask provides a url_for()
function to build URLs for specific functions:
url_for()
to generate URLs instead of hardcoding them. This makes your application more maintainable.
Redirects and Errors
Flask provides functions for redirecting and displaying error pages:
Templates with Jinja2
Template Basics
Flask uses Jinja2 as its template engine. Templates are HTML files with Jinja2 syntax for dynamic content. By convention, templates are stored in a templates
folder:
Rendering templates in Flask:
Jinja2 Syntax
Jinja2 provides several types of delimiters:
{{ ... }}
for expressions to print to the template output{% ... %}
for statements like loops or assignments{# ... #}
for comments
A simple Jinja2 template (index.html
):
Welcome to {{ title }}
{% if user %}Hello, {{ user.username }}!
{% else %}Hello, Guest!
{% endif %}Posts
-
{% for post in posts %}
- {{ post.title }} - {{ post.author }} {% else %}
- No posts available. {% endfor %}
Using this template in a view function:
Template Inheritance
Jinja2 supports template inheritance, which allows you to build a base template and extend it in child templates:
Base template (base.html
):
Child template (index.html
):
Welcome to My Website
This is the home page.
{% endblock %}Static Files
Flask looks for static files (CSS, JavaScript, images) in a static
folder:
Referencing static files in templates:
 }})
Handling Forms
Basic Form Handling
Flask provides access to form data through the request
object:
Flask-WTF for Forms
Flask-WTF is an extension that integrates WTForms with Flask, providing more structured form handling with validation:
Defining a form class:
Using the form in a view function:
Template for rendering the form (login.html
):
Login
{% with messages = get_flashed_messages() %} {% if messages %}-
{% for message in messages %}
- {{ message }} {% endfor %}
{{ form.hidden_tag() }}
in your form template. This generates a hidden field with a CSRF token for security.
Database Integration
Flask-SQLAlchemy
Flask-SQLAlchemy is an extension that adds SQLAlchemy support to Flask, making it easier to work with databases:
Setting up SQLAlchemy:
Defining Models
Models are Python classes that represent database tables:
Creating the Database
Create the database tables based on your models:
Basic CRUD Operations
Performing Create, Read, Update, Delete operations with SQLAlchemy:
Using Models in Views
Integrating database models with Flask views:
Migrations with Flask-Migrate
As your application evolves, you'll need to modify your database schema. Flask-Migrate (based on Alembic) helps manage database migrations:
Setting up Flask-Migrate:
Using Flask-Migrate from the command line:
Structuring Large Applications with Blueprints
What are Blueprints?
Blueprints are a way to organize your Flask application into modular components. They help you split your application into smaller, reusable parts that can be registered with the main application.
Creating a Blueprint
Let's create a blueprint for user-related routes:
Registering Blueprints
In your application factory or main file:
Recommended Project Structure
For larger Flask applications, a modular structure using blueprints is recommended:
Deployment
Preparing for Production
Before deploying a Flask application, make sure to:
- Disable debug mode:
app.run(debug=False)
- Use a production WSGI server (Gunicorn, uWSGI, etc.)
- Set up proper error logging
- Use environment variables for configuration
- Enable HTTPS
Deployment Options
1. Traditional Server with Gunicorn and Nginx
Configure Nginx as a reverse proxy:
2. Docker Deployment
Create a Dockerfile:
3. Platform as a Service (PaaS)
For simpler deployments, consider using services like:
- Heroku
- Railway
- Render
- DigitalOcean App Platform
- Google Cloud Run
Popular Flask Extensions
Flask-Login
User session management for Flask, providing user authentication and "remember me" functionality.
pip install flask-login
Flask-RESTful
Extension for quickly building REST APIs in Flask.
pip install flask-restful
Flask-Admin
Ready-to-use admin interface for Flask that can integrate with SQLAlchemy, MongoDB, and more.
pip install flask-admin
Flask-Mail
Makes sending emails from Flask applications simple.
pip install flask-mail
Flask-Caching
Adds caching support to your Flask application.
pip install flask-caching
Flask-JWT-Extended
JWT authentication support for Flask applications.
pip install flask-jwt-extended