Deploying Python web apps
Running fastapi dev or manage.py runserver on your laptop is for development only. Production needs a real application server, safe settings, a proper database, static files, logging and a way to run all of it reliably. This lesson is the checklist, ending with the track's capstone.
Application servers
| Framework | Run it with |
|---|---|
| FastAPI / Starlette | Uvicorn: uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4, or fastapi run |
| Django (WSGI) | Gunicorn: gunicorn mysite.wsgi --workers 4 --bind 0.0.0.0:8000 |
| Django (ASGI, for async views or WebSockets) | Uvicorn or Daphne: uvicorn mysite.asgi:application |
Each worker is a separate process handling requests, so a common starting point is about 2 × CPU cores for sync apps; async apps need fewer. In containers it's often simpler to run one worker per container and scale the number of containers.
In front of the app there is usually a reverse proxy or load balancer (nginx, Caddy, Traefik, or the cloud's load balancer) that terminates HTTPS, serves static files and spreads traffic.
Django's production settings
DEBUG = True shows detailed error pages with your settings and code. Never in production. Django can check your configuration for you:
Run python manage.py check --deploy before every release. A production settings.py reads secrets and environment-specific values from the environment:
import os
import dj_database_url # pip install dj-database-url
DEBUG = os.environ.get("DJANGO_DEBUG") == "1"
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"] # crash at startup if missing
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
DATABASES = {"default": dj_database_url.config(conn_max_age=600)} # from DATABASE_URL
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") # behind a proxy that terminates HTTPS
CSRF_TRUSTED_ORIGINS = ["https://myshop.example"]
STATIC_ROOT = BASE_DIR / "staticfiles" # collectstatic copies files here
STORAGES = {"staticfiles": {"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage"}}Static files (CSS, JavaScript, images) are collected with python manage.py collectstatic and served by WhiteNoise (simple), nginx, or a CDN / object storage (S3) with django-storages. User uploads (MEDIA) always go to object storage in production, never the container's disk.
FastAPI configuration with pydantic-settings
FastAPI apps typically load configuration with pydantic-settings, which reads environment variables (and .env files) into a typed, validated object:
from functools import lru_cache
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env")
database_url: str
jwt_secret: str
debug: bool = False
allowed_origins: list[str] = []
@lru_cache
def get_settings() -> Settings:
return Settings() # raises a clear error at startup if DATABASE_URL is missingUse it as a dependency (settings: Annotated[Settings, Depends(get_settings)]), and override it in tests.
The release steps
pip install -r requirements.txt # or: uv sync --frozen
python manage.py migrate --noinput # apply database migrations (Alembic: alembic upgrade head)
python manage.py collectstatic --noinput
gunicorn mysite.wsgi # start (or restart) the appRun migrations once per release (a separate step in your pipeline or a release command), not in every container at startup. And write migrations that are safe while the old version is still running: add a nullable column first, deploy, backfill, then make it required.
A Dockerfile for a Python web app
FROM python:3.14-slim
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["gunicorn", "mysite.wsgi", "--bind", "0.0.0.0:8000", "--workers", "3", "--access-logfile", "-"]PYTHONUNBUFFERED=1 makes logs appear immediately; running as a non-root user limits damage if the app is compromised. (See the Docker track for images, compose and registries.)
Where to host
| Option | Effort | Examples |
|---|---|---|
| Platform as a service | Lowest: push code or a container, they run it | Render, Railway, Fly.io, Heroku, Google Cloud Run, AWS App Runner |
| Containers on a cluster | Medium to high | AWS ECS, Kubernetes |
| A virtual machine | You manage everything | Ubuntu + nginx + gunicorn + systemd |
| Serverless functions | Good for spiky, small APIs | AWS Lambda with Mangum (ASGI adapter) |
Whatever you choose, use a managed PostgreSQL database (with automatic backups), a managed Redis for caching and task queues, and keep the app itself stateless so you can run several copies.
Observability
- Logging: structured (JSON) logs to standard output, with request IDs; collect them centrally.
- Errors: Sentry (or similar) captures exceptions with full context and alerts you.
- Metrics and traces: OpenTelemetry instrumentation for Django and FastAPI shows slow endpoints and database queries.
- Health checks: a
/healthendpoint that the load balancer calls.
🎓 Django & FastAPI track complete!
You've learned how Python web frameworks work (WSGI and ASGI), FastAPI routes, validation with Pydantic, databases with SQLModel, dependencies and testing; Django's ORM, views, templates, forms, admin and class-based views; Django REST framework; authentication in both frameworks; background tasks and async; and deploying to production.
Capstone project: a course-booking platform
Build it twice, or pick one framework and add one feature with the other:
- Django app: courses, sessions and bookings models; public pages with templates; the admin for staff; user accounts with django-allauth or Django's auth views.
- Rules: a session has a capacity; booking happens in a transaction with
select_for_update(), so it can never be overbooked; users can cancel up to 24 hours before. - API: a DRF (or FastAPI) API for a mobile app, with token authentication, pagination, filters (
?date=…&city=…) and an OpenAPI schema. - Background work: booking confirmation emails and a reminder the day before, through a task queue.
- Tests: pytest tests for booking rules, permissions and the API.
- Production: Docker image, PostgreSQL,
check --deploypassing, environment-based settings, Sentry, and a CI pipeline that runs tests and migrations.
1.Why must DEBUG be False in production?
2.Which server runs a FastAPI app in production?
3.Why keep the web app stateless (uploads in object storage, sessions in a database or Redis)?