Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 39 ยท Testing and Deployment

Production Settings and Deploying a DRF API

Prepare a Django REST Framework API for production: deployment checks, HTTPS settings, secrets, CORS, JSON-only renderers, gunicorn and nginx, static files, logging, health checks and a release checklist.

Your API works on your laptop. Production is a different world: strangers on the internet, many requests at once, secrets that must stay secret, and servers that restart at 3 a.m. This lesson is the checklist that turns a working DRF project into one you can safely deploy.

Nothing here is specific to one hosting company. The same ideas apply on a virtual machine, in Docker, on a platform service or on Kubernetes. We will use Django's built-in deployment check to find security gaps, set up CORS for browser front ends, add a request ID to logs and errors, and then look at the usual process layout.

From laptop to production

Secure settings DEBUG off, HTTPS, secrets from the environment
A real server gunicorn behind nginx or a platform router
Real services PostgreSQL, Redis cache, object storage
Eyes on it Logs, errors, health checks

runserver is for development only

1 / 2

Step 1: configuration from the environment

Never commit secrets. Read them from environment variables (or a secret manager) and keep one settings module that behaves correctly by default.

Python
# settings.py (read-only)
import os
from pathlib import Path

DEBUG = os.environ.get("DJANGO_DEBUG", "") == "1"          # off unless explicitly enabled
SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]                # crash at startup if missing
ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ["DB_NAME"],
        "USER": os.environ["DB_USER"],
        "PASSWORD": os.environ["DB_PASSWORD"],
        "HOST": os.environ.get("DB_HOST", "localhost"),
        "CONN_MAX_AGE": 60,          # reuse connections for a minute
    }
}

REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"],   # no browsable API
    "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.CursorPagination",
    "PAGE_SIZE": 50,
    "DEFAULT_THROTTLE_CLASSES": ["rest_framework.throttling.AnonRateThrottle", "rest_framework.throttling.UserRateThrottle"],
    "DEFAULT_THROTTLE_RATES": {"anon": "60/min", "user": "600/min"},
}

Reading os.environ["DJANGO_SECRET_KEY"] (square brackets) is deliberate: a missing secret should stop the application at boot, not run with a default that attackers know. Use a different secret for every environment, and rotate it if it ever leaks (rotation logs everyone out and invalidates signed data).

Step 2: run Django's deployment checks

Django ships with a checklist: python manage.py check --deploy. It inspects your settings for common security mistakes: missing HTTPS redirect, HSTS, insecure cookies, a weak secret key, DEBUG left on. You can run the same checks from code. The demo starts from sloppy settings, then applies the fixes.

Python check --deploy: from warnings to a clean bill

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.

Output:

TEXT
before: ['security.W004', 'security.W008', 'security.W009', 'security.W011', 'security.W016']
after:  []

Every ID in the first list is documented in Django's "System check framework" page; each one maps to a line in the hardened settings. Two details to understand rather than copy blindly:

  • SECURE_PROXY_SSL_HEADER tells Django that a request is HTTPS when your proxy says so in a header. Set it only when your proxy strips that header from outside requests; otherwise clients can lie about it.
  • SECURE_HSTS_PRELOAD and long HSTS lifetimes are hard to undo. Start with a small SECURE_HSTS_SECONDS such as 300 and raise it once you are sure every subdomain supports HTTPS.

Because DRF's token and JWT authentication do not use cookies, CSRF and cookie flags matter mostly for session login and the admin site. HTTPS still matters for everything: a token sent over plain HTTP can be stolen on any network between the client and you.

Step 3: CORS for browser front ends

A browser blocks JavaScript on https://app.example.com from reading responses from https://api.example.com unless the API says it is allowed. That permission is CORS (cross-origin resource sharing). Native apps and server-to-server calls do not need it. The standard package is django-cors-headers.

Python django-cors-headers: allowed and unknown origins

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.

Output:

TEXT
allowed origin                 200 {'Vary': 'Accept, origin', 'access-control-allow-origin': 'https://app.example.com'}
unknown origin                 200 {'Vary': 'Accept, origin'}
preflight from allowed origin  200 {'Vary': 'origin', 'access-control-allow-origin': 'https://app.example.com', 'access-control-allow-headers': 'authorization, content-type', 'access-control-allow-methods': 'DELETE, GET, OPTIONS, PATCH, POST, PUT', 'access-control-max-age': '86400'}

Rules of thumb for CORS:

  • List exact origins in CORS_ALLOWED_ORIGINS. Avoid CORS_ALLOW_ALL_ORIGINS = True on anything with credentials.
  • CORS does not authenticate anyone. It only tells browsers what pages may read. The API must still check tokens and permissions.
  • Put CorsMiddleware above any middleware that can return a response (such as CommonMiddleware), so error responses also carry the headers.
  • Access-Control-Allow-Origin: * is fine for a fully public read-only API without cookies.

Step 4: logs, error ids and error reporting

When something fails at 3 a.m. you want one line in the log that matches the error a user reports. A small middleware assigns each request an ID, returns it in a header, and a custom DRF exception handler puts the same ID into error bodies.

Python A request ID in the logs and in every error response

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.

Output:

TEXT
404 req-0001 {'error': {'detail': 'No such report.'}, 'request_id': 'req-0001'}
404 req-0002 {'error': {'detail': 'No such report.'}, 'request_id': 'req-0002'}
log lines: ['req-0001 GET /boom/ -> 404', 'req-0002 GET /boom/ -> 404']

In production, send these logs as JSON lines to a log service, and connect an error tracker such as Sentry, which captures unhandled exceptions with their stack traces and the same request ID. Set LOGGING so Django's django.request and django.security loggers are not silent, and never log passwords, tokens or full request bodies.

Step 5: processes, static files and the database

DRF is a normal WSGI (or ASGI) application, so you run it as one:

TEXT
# read-only: a typical layout
client -> nginx / load balancer (TLS, buffering) -> gunicorn (4 workers) -> Django + DRF -> PostgreSQL
                                                                                   \-> Redis (cache, throttles)
Terminal
# read-only
pip install gunicorn
gunicorn config.wsgi:application --workers 4 --timeout 30 --bind 0.0.0.0:8000
  • Workers. A starting point is 2 * CPU cores + 1 synchronous workers. Use threads or ASGI (uvicorn/daphne) if requests wait a lot on outside services.
  • Static files. The admin and the browsable API need CSS and JavaScript. Run python manage.py collectstatic at build time and serve the folder with nginx, a CDN, or WhiteNoise middleware. A JSON-only API without the admin needs none.
  • Database. Use PostgreSQL (or MySQL), not SQLite, with CONN_MAX_AGE or a pooler such as PgBouncer. Back it up and test the restore.
  • Shared cache. Throttles, caching and rate counters must use Redis or Memcached, not per-process memory (see throttling).
  • Migrations. Run python manage.py migrate as a separate release step, before starting new code. Write backward-compatible migrations (add columns first, remove them in a later release) so old and new code can run together during a rolling deploy.
  • Background work. Slow tasks (email, reports, webhooks) belong in a queue (Celery, RQ, Dramatiq), not in the request.

A minimal container, again read-only because this site cannot run Docker:

DOCKERFILE
FROM python:3.13-slim
ENV PYTHONUNBUFFERED=1
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN python manage.py collectstatic --noinput
USER nobody
CMD ["gunicorn", "config.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "4"]

Step 6: health checks and release checklist

Load balancers and orchestrators need a cheap URL that says "this instance can serve traffic": a tiny view that returns 200, optionally after a SELECT 1. Keep it unauthenticated, unthrottled and out of your API docs.

Before every release, confirm:

  1. python manage.py check --deploy is clean and DEBUG is off.
  2. Tests pass, including permission and query-count tests (testing lessons).
  3. Migrations were run and reviewed for locks on big tables.
  4. Secrets come from the environment and differ per environment.
  5. Only JSON renderers are enabled, pagination and throttling are set globally.
  6. CORS lists exact origins; HTTPS is enforced everywhere.
  7. The OpenAPI schema is regenerated and committed (schema generation).
  8. Logs, error tracking and uptime monitoring are connected, and you know how to roll back.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does python manage.py check --deploy do?

    It runs Django's deployment-specific system checks, such as HTTPS redirect, HSTS, secure cookies and DEBUG.
  2. 2. Why read SECRET_KEY with os.environ['DJANGO_SECRET_KEY'] and no default?

    Failing loudly at boot is safer than silently using a guessable value.
  3. 3. What does CORS protect or allow?

    CORS is a browser rule about reading cross-origin responses. It does not replace authentication or permissions.
  4. 4. Where should throttle counters live in production with several worker processes?

    Local memory caches are per process, so limits would be multiplied by the number of workers.
  5. 5. Why use a request ID in logs and error responses?

    The same ID in the response header, body and log line makes incidents easy to trace.

Summary

  • Read configuration and secrets from the environment, keep DEBUG off, and fail loudly when a secret is missing.
  • Run check --deploy, enforce HTTPS with HSTS and secure cookies, and set SECURE_PROXY_SSL_HEADER only behind a trusted proxy.
  • Use django-cors-headers with exact origins; CORS is not authentication.
  • Add request IDs, structured logs and an error tracker.
  • Serve with gunicorn behind a proxy, use PostgreSQL and a shared cache, run migrations as a separate step, and add a health check.
  • Release with a checklist: tests, security checks, schema, rollback plan.

Next: Project: A Bookstore API