Django Integration Guide
Koreshield can protect Django applications using middleware to intercept and inspect requests before they reach your views.
Installation
pip install Koreshield django
Middleware Setup
Create a file named middleware.py in one of your apps (e.g., yourapp/middleware.py):
import asyncio
import json
from django.http import JsonResponse
from django.conf import settings
from Koreshield.client import KoreshieldClient
class KoreshieldMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.client = KoreshieldClient(
base_url=getattr(settings, "Koreshield_URL", "http://localhost:8000")
)
self.protected_paths = getattr(settings, "Koreshield_PROTECTED_PATHS", [])
def __call__(self, request):
if request.path in self.protected_paths and request.method == "POST":
try:
# Basic body parsing - adjust based on your needs
body = json.loads(request.body)
prompt = body.get("message") or body.get("prompt")
if prompt:
# Sync wrapper around async call
is_safe = asyncio.run(self._check_safety(prompt))
if not is_safe["is_safe"]:
return JsonResponse({
"error": "Blocked by Koreshield",
"reason": is_safe["reason"]
}, status=403)
except Exception:
pass
return self.get_response(request)
async def _check_safety(self, prompt):
result = await self.client.guard(prompt)
return {"is_safe": result.is_safe, "reason": result.reason}
Configuration
In your settings.py:
MIDDLEWARE = [
# ...
'yourapp.middleware.KoreshieldMiddleware',
]
Koreshield_URL = "http://localhost:8000"
Koreshield_PROTECTED_PATHS = ["/api/v1/chat", "/api/v1/generate"]
Notes
- For high-performance async Django (Generic Async Views), use
__acall__instead of__call__. - Ensure
KoreshieldProxyis reachable from your Django backend.