Frameworks12 min read
Deploy Python / Django
Deploy Python applications including Django, FastAPI, and Flask with dependency management and process management.
1.Requirements.txt and pyproject.toml
Manage Python dependencies with modern tooling.
- Use requirements.txt for pip: pip freeze > requirements.txt
- Or pyproject.toml with [project] and [tool.poetry] or [tool.uv]
- Pin versions for reproducible builds: django==4.2.*
- Separate dev dependencies: requirements-dev.txt
2.Django Settings for Production
Configure Django for secure production deployment.
- Set DEBUG=False and ALLOWED_HOSTS from env
- Use dj-database-url to parse DATABASE_URL
- Configure STATIC_ROOT and MEDIA_ROOT
- Use django-environ or python-decouple for env parsing
- Enable security middleware: SECURE_SSL_REDIRECT=True, SECURE_HSTS_SECONDS
# settings/production.py
import environ
env = environ.Env()
DEBUG = env.bool("DEBUG", default=False)
ALLOWED_HOSTS = env.list("ALLOWED_HOSTS")
SECRET_KEY = env("SECRET_KEY")
DATABASES = {"default": env.db("DATABASE_URL")}
SECURE_SSL_REDIRECT = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True3.Gunicorn/Uvicorn Configuration
Configure ASGI/WSGI server for production.
- Django/Flask (WSGI): gunicorn --bind 0.0.0.0:$PORT --workers 4 --worker-class gthread myproject.wsgi
- FastAPI/Starlette (ASGI): uvicorn main:app --host 0.0.0.0 --port $PORT --workers 4
- Use --preload for faster worker startup
- Set --timeout 120 for long requests
- Access logs: --access-logfile -
# Gunicorn config (gunicorn.conf.py)
bind = "0.0.0.0:8000"
workers = 4
worker_class = "gthread"
threads = 2
preload_app = True
timeout = 120
accesslog = "-"
errorlog = "-"
# Uvicorn for FastAPI
# uvicorn main:app --host 0.0.0.0 --port $PORT --workers 44.Static and Media Files
Serve static and media files efficiently.
- Run python manage.py collectstatic --noinput in build step
- Set STATIC_ROOT = /app/staticfiles
- Media files: use MEDIA_ROOT outside code directory
- In production, serve static via nginx or CDN (Oxaploy handles this)
- Media files: configure separate storage (S3, local volume)