A Django view that scores a submitted message with Siftfy before sending email or queuing moderation.
main.pypython
python
# pip install requestsimport os
import requests
from django.http import JsonResponse
from django.views.decorators.http import require_POST
@require_POSTdefcontact(request):
email = request.POST.get("email", "")
message = request.POST.get("message", "")
ifnot email ornot message:
return JsonResponse({"error": "email and message required"}, status=400)
probability = 0.0try:
resp = requests.post(
"https://api.siftfy.io/v1/predict",
headers={"X-API-Key": os.environ["SIFTFY_KEY"]},
json={"text": message},
timeout=2,
)
if resp.ok:
probability = resp.json()["spam_probability"]
except requests.RequestException:
probability = 0.0if probability >= 0.85:
return JsonResponse({"ok": True})
if probability >= 0.50:
queue_for_review(email=email, message=message, probability=probability)
else:
deliver_to_inbox(email=email, message=message)
return JsonResponse({"ok": True})
Production notes
01For async Django views, use httpx.AsyncClient and the same thresholds.
02Do not return a spam-specific error to the browser.
03Store probability and action for audits, not the full body unless your privacy policy allows it.
Common questions
How do I integrate Siftfy spam detection with Django?
POST the form's `message` field to `https://api.siftfy.io/v1/predict` from inside a Django view, then branch on the returned `spam_probability`. Use `requests` for sync views or `httpx.AsyncClient` for async views. The full view is shown above.
Where should the Siftfy API key live in a Django project?
Read it from an environment variable via `os.environ['SIFTFY_KEY']` or `django-environ` and reference it from `settings.py`. Never commit the key to source control.
How do I avoid blocking the request thread on Siftfy calls?
Use Django 4.1+ async views with `httpx.AsyncClient`, or move the call into a background task with Celery / Django-Q when latency budget is tight. Keep the timeout under 2 seconds either way.
Should Django log full message bodies for spam audits?
Log the probability, the action you took, and request metadata, but avoid logging full message bodies unless your privacy policy permits it. Truncated previews are usually enough for false-positive review.