Django Integration Guide
The ztlayer-django package provides a native Django Middleware component that intercepts HTTP requests, queries the ZTLayer Edge network asynchronously, and blocks malicious traffic before it reaches your URLs or Views.
1. Installation
Install the package via pip.
pip install ztlayer-django2. Configuration
Add your ZTLayer API Key to your Django settings.py file. It is strongly recommended to load this from your environment variables.
# settings.py
import os
ZTLAYER_API_KEY = os.environ.get('ZTLAYER_API_KEY')
# Optional Settings
ZTLAYER_FAIL_MODE = 'open' # 'open' (default) or 'closed'
ZTLAYER_TIMEOUT_MS = 15003. Registering the Middleware
Add the ZTLayer middleware to your MIDDLEWARE list in settings.py.
[!IMPORTANT] The order of middleware matters. You must place
ZeroTrustMiddlewareafter theSecurityMiddlewareandCommonMiddleware, but beforeCsrfViewMiddlewareandAuthenticationMiddleware. This ensures threats are blocked before expensive DB lookups or CSRF checks occur.
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 1. Add ZTLayer Middleware here
'ztlayer_django.middleware.ZeroTrustMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]4. Bypassing Specific Routes
In many Django applications, you may want to exclude specific paths (like Django Admin or Stripe Webhooks) from the global security inspection.
You can define an exclusion list in your settings.py. These paths are evaluated using regex.
# settings.py
ZTLAYER_EXCLUDE_PATHS = [
r'^/admin/', # Bypass Django Admin
r'^/stripe/webhook/', # Bypass Server-to-Server Webhooks
r'^/static/', # Bypass static assets
]5. Trusting Reverse Proxies (Critical)
If you deploy your Django app behind Gunicorn + Nginx, AWS ALB, or Heroku, Django's request.META['REMOTE_ADDR'] will show the internal IP of the proxy.
ZTLayer relies on the true client IP to enforce rate limits and geo-fencing. You must ensure you are using a proxy-aware middleware (like django-ipware) to extract the real IP, or configure ZTLayer to look for the X-Forwarded-For header.
# settings.py
ZTLAYER_TRUST_PROXY_HEADER = 'HTTP_X_FORWARDED_FOR'