Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 149 ยท Data and the Web

Web Development with Flask and Django

Discover how Python builds websites and APIs. Learn what web frameworks do, how WSGI, routing and templates work, and compare Flask, Django and FastAPI.

Some of the busiest sites on the internet run Python on their servers. When you open a page, a Python program receives your request, decides what you asked for, loads data from a database, fills it into an HTML template and sends the result back. That program is almost always built with a web framework, a library that handles the repetitive plumbing so you can focus on what your site actually does.

This lesson shows you what happens inside a framework by building tiny working versions of its main parts: the server interface, routing, templates and a JSON API. Then you'll see how the two most popular frameworks, Flask and Django, provide the real thing, and where FastAPI fits in.

What runs here and what doesn't. The editors on this page can't open a network port, so they can't host a real website. The live examples call the web application code directly, playing the role of the web server. Flask and Django code is shown as read-only snippets for you to run on your own computer.

What a web framework does

Every web request goes through the same steps, whatever the site:

  1. A web server receives the raw HTTP request (see Networking: URLs, HTTP and Sockets).
  2. It hands the request to your application.
  3. Routing picks the function (often called a view) that handles that URL and method.
  4. The view reads input, talks to the database, applies the business rules and makes the response: an HTML page from a template, or JSON for an API.
  5. The server sends the response back.

A framework provides steps 2 to 5 as ready-made, tested pieces, plus things almost every site needs: form handling, sessions and login, security protections, error pages and settings for different environments.

WSGI: how servers talk to Python

Python web servers and frameworks agree on a standard interface called WSGI (Web Server Gateway Interface). A WSGI application is just a callable with two parameters:

  • environ, a dictionary describing the request: method, path, query string, headers.
  • start_response, a function the app calls with the status and response headers.

The app returns the response body as an iterable of bytes. That's the whole contract. Here's a complete web application, plus a few lines that do the web server's job by building an environ and calling it:

Python A complete WSGI application

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Real servers such as Gunicorn or uWSGI do exactly what fake_request() does, but for real network connections, thousands of times per second, across several worker processes. Because of WSGI, any server can run any framework: Flask and Django apps are WSGI apps underneath.

A newer standard, ASGI (Asynchronous Server Gateway Interface), plays the same role for async apps and adds support for long-lived connections such as WebSockets. ASGI servers include Uvicorn and Hypercorn.

Routing

Writing one big if/elif chain for every URL doesn't scale. Frameworks let you attach a function to a URL pattern, usually with a decorator. Patterns can contain variable parts, like /books/<book_id>, that become function arguments.

Here's a toy router built with a decorator and regular expressions. It works the same way Flask's does:

Python A tiny router with decorators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The decorator doesn't change the view function at all. It just records "this pattern and method belong to this function". Notice the two different errors: 404 when no route matches the path, and 405 when the path exists but not for that method.

Templates and escaping

Building HTML with f-strings quickly gets messy, so frameworks use template engines: HTML files with placeholders and simple loops. Flask uses Jinja2, and Django has its own template language with a very similar syntax:

HTML
<!-- templates/results.html (Jinja2) -->
<h1>Results for "{{ query }}"</h1>
<ul>
  {% for book in books %}
    <li>{{ book.title }} ({{ book.year }})</li>
  {% else %}
    <li>No books found.</li>
  {% endfor %}
</ul>

Templates have one more crucial job: escaping. Anything a user typed must be shown as text, never run as HTML. Otherwise an attacker can put a <script> into a search box or a comment, and it runs in every visitor's browser. This attack is called cross-site scripting (XSS). Jinja2 (in Flask) and Django templates escape values automatically.

The standard library's html.escape() shows what that escaping does:

Python Why templates escape values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Escaping turns <, >, & and quotes into HTML entities such as &lt;, so the browser shows them as characters. It also fixes innocent text: Cooking for <one> would otherwise vanish as an unknown tag. You'll find more about how browsers read these characters in HTML Entities.

JSON APIs

Many Python web apps don't send HTML at all. They serve a REST API: URLs that represent resources (/tasks, /tasks/7), HTTP methods that act on them, and JSON in both directions. Mobile apps, JavaScript front ends and other servers call these APIs.

The conventions are simple:

Request Meaning Typical success status
GET /tasks list all tasks 200 OK
POST /tasks create a task from the JSON body 201 Created
GET /tasks/7 read one task 200 OK
PATCH /tasks/7 change some fields 200 OK
DELETE /tasks/7 delete it 204 No Content

This function implements that API on top of a dictionary. A framework would handle the routing and JSON conversion for you, but the logic is the same:

Python A small REST API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

422 Unprocessable Content signals that the JSON arrived but failed validation. Real APIs validate every field, and PATCH here trusts its input far too much. Frameworks and libraries such as Pydantic help with that.

Flask: a small, flexible framework

Flask is a "micro" framework: it gives you routing, request and response objects, Jinja2 templates and a development server, and leaves everything else (database, forms, login) to extensions you choose. That makes it quick to learn and great for small sites, APIs and prototypes.

Install it in a virtual environment with pip install flask, save this as app.py, and run flask --app app run --debug:

Python
from flask import Flask, abort, render_template, request

app = Flask(__name__)

BOOKS = {
    1: {"title": "The Silent Orchard", "year": 2019},
    2: {"title": "Maps of Salt", "year": 2021},
}

@app.get("/")
def home():
    return "<h1>Bookshop</h1>"

@app.get("/books/<int:book_id>")                 # <int:...> converts the value
def show_book(book_id: int):
    book = BOOKS.get(book_id) or abort(404)
    return render_template("book.html", book=book)   # templates/book.html

@app.get("/search")
def search():
    query = request.args.get("q", "")            # ?q=... from the URL
    found = [b for b in BOOKS.values() if query.lower() in b["title"].lower()]
    return render_template("results.html", query=query, books=found)

@app.get("/api/books")
def api_books():
    return list(BOOKS.values())                  # lists and dicts become JSON

@app.post("/api/books")
def create_book():
    data = request.get_json()
    new_id = max(BOOKS) + 1
    BOOKS[new_id] = {"title": data["title"], "year": data["year"]}
    return BOOKS[new_id], 201                    # body and status code

Open http://127.0.0.1:5000/ in your browser. You'll recognize every idea from this lesson: decorators for routes, URL variables, templates, JSON and status codes. The development server is for development only. In production, Flask runs behind a WSGI server such as Gunicorn.

Django: batteries included

Django takes the opposite approach: it includes almost everything a large site needs, all designed to work together:

  • an ORM that maps Python classes to database tables, with migrations that update the schema as your models change (compare with raw SQL in Databases with sqlite3),
  • an automatic admin site for managing data,
  • forms, user accounts and authentication, sessions, caching and email,
  • built-in protections against SQL injection, XSS, cross-site request forgery (CSRF) and clickjacking.

A Django project is made of apps, each a folder with a standard layout. You create them with commands:

TEXT
pip install django
django-admin startproject bookshop .
python manage.py startapp catalog
python manage.py makemigrations     # turn model changes into a migration file
python manage.py migrate            # apply migrations to the database
python manage.py createsuperuser    # an account for the admin site
python manage.py runserver          # development server on port 8000

The core pieces of an app look like this:

Python
# catalog/models.py: database tables as classes
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    year = models.PositiveIntegerField()
    price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self) -> str:
        return self.title


# catalog/views.py: functions that take a request and return a response
from django.shortcuts import get_object_or_404, render
from .models import Book

def book_list(request):
    books = Book.objects.filter(year__gte=2020).order_by("title")   # safe SQL
    return render(request, "catalog/book_list.html", {"books": books})

def book_detail(request, pk: int):
    book = get_object_or_404(Book, pk=pk)
    return render(request, "catalog/book_detail.html", {"book": book})


# catalog/urls.py: routing
from django.urls import path
from . import views

urlpatterns = [
    path("books/", views.book_list, name="book-list"),
    path("books/<int:pk>/", views.book_detail, name="book-detail"),
]

Book.objects.filter(year__gte=2020) is the ORM at work: it generates a parameterized SELECT ... WHERE year >= ? query for you. For APIs, the popular Django REST Framework adds serializers and API views on top of Django.

FastAPI and choosing a framework

FastAPI is a newer ASGI framework designed for APIs. It reads your type hints to validate request data and to generate interactive API documentation automatically:

Python
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class TaskIn(BaseModel):
    title: str
    done: bool = False

@app.post("/tasks", status_code=201)
async def create_task(task: TaskIn) -> TaskIn:
    return task            # invalid JSON gets a 422 response automatically

How to choose:

If you want... Consider
A full website with users, an admin and a database, built fast Django
A small site, a prototype, or full control over each piece Flask
A typed JSON API, with async support and automatic docs FastAPI

All three are mature, well documented and widely used. The concepts you practiced here (requests, routing, templates with escaping, JSON, status codes, parameterized database access) carry over to every one of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a WSGI application?

    WSGI is the standard interface between Python web servers and applications. Flask and Django apps are WSGI applications underneath.
  2. 2. In Flask, what does @app.get("/books/<int:book_id>") do?

    The decorator records a route. The int converter turns the URL segment into an integer argument for the view function.
  3. 3. Why do template engines escape values by default?

    Escaping turns characters like < and & into entities, so text typed by users is shown, never executed.
  4. 4. Which status code should a REST API return after successfully creating a resource with POST?

    201 Created signals that a new resource exists. The response body usually contains it, including its new id.
  5. 5. Which framework includes an ORM, migrations and an automatic admin site out of the box?

    Django is "batteries included". Flask and FastAPI add databases and admin tools through separate packages, and WSGI is an interface, not a framework.

Summary

  • A web framework routes each request to a view, which builds a response from data, templates or JSON.
  • WSGI (and its async cousin ASGI) is the standard contract between Python web servers and applications.
  • Routing maps URL patterns and HTTP methods to functions, usually with decorators; 404 means no matching path, 405 a wrong method.
  • Templates fill HTML with data and escape user input to prevent XSS.
  • REST APIs use resource URLs, HTTP methods, JSON bodies and meaningful status codes.
  • Flask is small and flexible, Django is batteries-included with an ORM and admin, and FastAPI is built for typed async APIs.

Next: NumPy Basics, where you'll crunch numbers in whole arrays at once.