Django — full setup
Complete Django integration: middleware, OpenAI in views, environment config, shutdown.
Install
bash
pip install amlexia django openaiEnvironment
env
AMLEXIA_SDK_KEY=am_...
AMLEXIA_INGEST_URL=https://ingest.amlexia.com
AMLEXIA_ENVIRONMENT=production
AMLEXIA_SERVICE_NAME=api
DJANGO_SECRET_KEY=...
OPENAI_API_KEY=sk-...Settings (myproject/settings.py)
python
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"amlexia.django_integration.AmlexiaMiddleware",
"django.middleware.common.CommonMiddleware",
# ... rest of your middleware
]AmlexiaMiddleware uses AmlexiaClient.from_env() and AMLEXIA_SERVICE_NAME (default api).
Optional explicit client
python
from amlexia import AmlexiaClient
AMLEXIA_CLIENT = AmlexiaClient.from_env()
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
# Custom wrapper if you inject client — otherwise default middleware is enough
"amlexia.django_integration.AmlexiaMiddleware",
]Views (myapp/views.py)
python
import time
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from openai import OpenAI
from amlexia import AmlexiaClient
from amlexia.openai_helper import track_openai_completion
client = AmlexiaClient.from_env()
openai = OpenAI()
@require_http_methods(["GET"])
def health(request):
return JsonResponse({"ok": True})
@require_http_methods(["GET"])
def get_user(request, user_id):
return JsonResponse({"id": user_id})
@csrf_exempt
@require_http_methods(["POST"])
def stripe_webhook(request):
return JsonResponse({"received": True})
@csrf_exempt
@require_http_methods(["POST"])
def chat(request):
import json
body = json.loads(request.body)
start = time.time()
try:
completion = openai.chat.completions.create(
model="gpt-4o-mini",
messages=body["messages"],
)
track_openai_completion(
client,
model=completion.model,
status_code=200,
latency_ms=int((time.time() - start) * 1000),
usage=completion.usage,
)
return JsonResponse(completion.model_dump())
except Exception as e:
client.track(
endpoint="POST /api/chat",
method="POST",
status_code=500,
latency_ms=int((time.time() - start) * 1000),
provider="openai",
error_message=str(e)[:500],
)
return JsonResponse({"error": str(e)}, status=500)URLs (myapp/urls.py)
python
from django.urls import path
from . import views
urlpatterns = [
path("health/", views.health),
path("api/users/<int:user_id>/", views.get_user),
path("webhooks/stripe/", views.stripe_webhook),
path("api/chat/", views.chat),
]Middleware behavior
| Feature | Detail |
|---|---|
| Tracing | traceparent on response |
| Paths | Normalized (/users/42/ → /users/:id/) |
| Session | HTTP_X_SESSION_ID, HTTP_X_USER_ID |
| Provider | Auto-detect from path hints |
Place after SecurityMiddleware, before view runs.
Shutdown (ASGI / management commands)
For long-running runserver or gunicorn, register shutdown on worker exit:
python
# myproject/apps.py or wsgi.py
import atexit
from amlexia import AmlexiaClient
_client = AmlexiaClient.from_env()
atexit.register(_client.shutdown)Or call client.shutdown() in gunicorn worker_exit hook.
Verify
bash
amlexia health
python manage.py runserver
curl http://127.0.0.1:8000/health/