Integrations
Django
Integrate KoreShield with Django applications
Django Integration Guide
KoreShield can protect Django applications using middleware to intercept and inspect requests before they reach your views.
Installation
pip install koreshield djangoMiddleware 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.