AI-powered middleware for Django β security, rate limiting, anomaly detection, and log analysis. Drop it in. Configure once. Forget about it.
Every Django app eventually needs the same things:
- π Block malicious requests before they touch your views
- π€ Detect bots and scrapers automatically
- π³ Enforce subscription plan limits without writing boilerplate
- π Understand what happened in your app β in plain English
Smart Layer gives you all of this in one pip install.
No external services. No accounts. No infrastructure.
Just add it to MIDDLEWARE and you're protected.
| Middleware | Job | AI? |
|---|---|---|
AIAnomalyDetector |
Detects bots and attack patterns | β |
AIRequestValidator |
Blocks SQL injection, XSS, prompt injection | β |
RateLimiter |
Enforces per-plan, per-path request limits | β |
WatchLog |
Logs every request to your database | β |
analyse_logs |
Morning report β plain English summary | β |
Incoming Request
β
βΌ
βββββββββββββββββββββββββ
β AIAnomalyDetector β Is this user a bot? Suspicious pattern?
βββββββββββββ¬ββββββββββββ Blocked β 403
β
βΌ
βββββββββββββββββββββββββ
β AIRequestValidator β Is this payload malicious?
βββββββββββββ¬ββββββββββββ Blocked β 403
β
βΌ
βββββββββββββββββββββββββ
β RateLimiter β Is this user over their plan limit?
βββββββββββββ¬ββββββββββββ Blocked β 429
β
βΌ
βββββββββββββββββββββββββ
β WatchLog β Log everything β always runs
βββββββββββββ¬ββββββββββββ
β
βΌ
Your Django View β
Only clean requests reach here.
Every morning β python manage.py analyse_logs
Plain English report saved to Django admin
pip install django-smart-layerWith auto-scheduling support:
pip install django-smart-layer[scheduler]INSTALLED_APPS = [
...
'smartlayer',
]
MIDDLEWARE = [
'smartlayer.middleware.AIAnomalyDetector', # 1st β bot detection
'smartlayer.middleware.AIRequestValidator', # 2nd β payload validation
'smartlayer.middleware.RateLimiter', # 3rd β rate limiting
'smartlayer.middleware.WatchLog', # 4th β logging (always last)
...
]python manage.py migrateSMART_MIDDLEWARE = {
# ββ AI Backend ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
'AI_API_KEY': 'your-api-key',
'AI_BASE_URL': 'https://api.groq.com/openai/v1',
'AI_MODEL': 'llama3-8b-8192',
# ββ Rate Limiter βββββββββββββββββββββββββββββββββββββββββββββββββββββ
'PLAN_FIELD': 'plan', # field name on your User model β e.g. user.plan
'RATE_LIMIT_PLANS': {
'free': {
'/api/generate/': {'per_minute': 2, 'per_day': 50},
},
'basic': {
'/api/generate/': {'per_minute': 10, 'per_day': 500},
'/api/export/': {'per_minute': 5, 'per_day': 100},
},
'premium': {
'/api/generate/': {'per_minute': 50, 'per_day': 5000},
'/api/export/': {'per_minute': 20, 'per_day': 1000},
'/api/analytics/':{'per_minute': 100, 'per_day': 10000},
},
},
# ββ Log Analysis βββββββββββββββββββββββββββββββββββββββββββββββββββββ
'LOG_RETENTION_DAYS': 30, # auto delete logs older than 30 days
'ANALYSE_LOGS_AT': '06:00', # auto run report daily at 6am (needs apscheduler)
}That's it. Your app is protected. β
Watches request patterns and blocks bots before they can do damage.
Three instant block rules:
1. Empty user agent β block immediately
2. 50+ requests in 10 seconds β block immediately
3. 75%+ errors in last 2 minutes β block immediately
Suspicion scoring for subtle attacks:
| Signal | Score |
|---|---|
| Suspicious user agent (curl, scrapy, wget...) | +2 |
| Elevated request rate (20β49 in 10s) | +3 |
| Moderate error rate (40β74%) | +2 |
| Hitting sensitive paths (/admin, /.env) | +4 |
| Scanning 15+ distinct endpoints per minute | +2 |
| Sequential ID probing (/users/1, /users/2...) | +5 |
| Burst after long idle on same endpoint | +2 |
Score β₯ 8 β blocked immediately. Score 4β7 β AI asked in background. Banned on next request if AI says BLOCK.
β‘ New users get a grace period β first 20 requests are never scored. Legitimate users exploring your app are never penalised.
Returns: 403 Forbidden
Scans every request body for attacks before they reach your views.
Stage 1 β Pattern matching (instant, free)
Detects SQL injection, XSS, path traversal, shell injection, prompt injection, null bytes, and encoding tricks.
Score 0 β safe, no AI call needed
Score 1β2 β borderline, sent to AI
Score 3+ β obviously malicious, blocked immediately
Stage 2 β AI analysis (only for borderline requests)
Catches clever attacks that bypass regex: encoded attacks, split-field attacks, business logic abuse, social engineering, and obfuscated payloads.
Confidence > 85% β blocked.
π‘ File uploads (multipart) are skipped automatically.
Returns: 403 Forbidden
Enforces per-user, per-plan, per-path limits. Built for SaaS.
Supports four limit types β use any combination:
'RATE_LIMIT_PLANS': {
'free': {
'/api/generate/': {
'per_minute': 2,
'per_hour': 20,
'per_day': 100,
'lifetime': 1000, # never resets
},
},
}Key behaviours:
- Routes only in
premiumautomatically return403for lower plan users - Each plan gets independent counters β upgrading starts fresh
- Cache-based counting β zero extra DB load for time-based limits
- Lifetime limits use atomic DB increments β race condition safe
Returns: 429 Too Many Requests
Silently records every request to the database. Zero configuration needed.
Writes happen in a background thread β response returns instantly, database write happens after. Zero performance impact.
What gets saved:
| Field | Example |
|---|---|
method |
GET |
path |
/api/generate/ |
status_code |
200 |
response_time_ms |
143.2 |
timestamp |
2024-01-15 14:32:01 |
user_id |
42 (authenticated users) |
ip_address |
192.168.1.1 (anonymous only) |
was_blocked |
True / False |
Reads yesterday's logs and writes a plain English report using AI.
python manage.py analyse_logsWhat it covers:
- Overall API health assessment
- Error rate and what it means
- Slowest endpoints and likely causes
- Suspicious activity worth investigating
- 2β3 clear actionable recommendations
Report saved to Django admin β Daily Reports. Always accessible.
Auto cleanup: Logs older than LOG_RETENTION_DAYS deleted automatically.
Your database never grows out of control.
Auto schedule (requires apscheduler):
SMART_MIDDLEWARE = {
...
'ANALYSE_LOGS_AT': '06:00', # runs every day at 6am automatically
}Or use cron:
0 6 * * * /path/to/venv/bin/python /path/to/manage.py analyse_logsWorks with any OpenAI-compatible provider:
| Provider | AI_BASE_URL |
Notes |
|---|---|---|
| Groq | https://api.groq.com/openai/v1 |
Fast, generous free tier β recommended |
| OpenAI | https://api.openai.com/v1 |
Most capable |
| Gemini | https://generativelanguage.googleapis.com/v1beta/openai |
Google free tier |
| Ollama | http://localhost:11434/v1 |
Fully local, completely free |
π‘
RateLimiterandWatchLogneed zero AI configuration. OnlyAIAnomalyDetector,AIRequestValidator, andanalyse_logsneed a key.
SMART_MIDDLEWARE = {
# AI β required for AI middlewares and analyse_logs
'AI_API_KEY': 'your-key',
'AI_BASE_URL': 'https://api.groq.com/openai/v1',
'AI_MODEL': 'llama3-8b-8192',
# RateLimiter
'PLAN_FIELD': 'plan', # field name on User model
'RATE_LIMIT_PLANS': {
'free': {
'/api/generate/': {
'per_minute': 2,
'per_hour': 20,
'per_day': 100,
'lifetime': 1000,
},
},
'premium': {
'/api/generate/': {
'per_minute': 50,
'per_day': 5000,
},
},
},
# analyse_logs
'LOG_RETENTION_DAYS': 30, # default: 30
'ANALYSE_LOGS_AT': '06:00', # remove to use cron instead
# AIAnomalyDetector β optional tuning
'grey_suspicion_threshold': 4,
'grey_hard_block_score': 8,
'grey_sensitive_paths': [
'/admin', '/.env', '/api/token',
],
}- Python 3.10+
- Django 4.2+
httpxβ installed automaticallyapschedulerβ optional, only forANALYSE_LOGS_AT
| Limitation | Workaround |
|---|---|
| Coordinated attacks from many IPs | Use Cloudflare or AWS WAF in front |
| Slow drip attacks (1 req/hour over days) | Will appear in analyse_logs report |
| AI backend unreachable | All middleware fails open β app never breaks |
| Cache resets on server restart | Use Redis cache for persistent rate limiting |
- Usage dashboard at
/smart-layer/usage/ - Grey-zone AI analysis in
AIAnomalyDetector - Email delivery for daily reports
- Test suite
MIT β free to use, modify, and distribute.
Built for Django developers who want real protection without the complexity.