AI-powered Django middleware for security, monitoring and rate limiting
Project description
๐ก๏ธ django-smart-layer
AI-powered middleware for Django โ security, rate limiting, anomaly detection, and log analysis. Drop it in. Configure once. Forget about it.
Why django-smart-layer?
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.
What's Inside
| 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 | โ |
How It All Fits Together
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
Quick Start
1. Install
pip install django-smart-layer
With auto-scheduling support:
pip install django-smart-layer[scheduler]
2. Add to settings
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)
...
]
3. Run migrations
python manage.py migrate
4. Configure
SMART_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. โ
Middleware โ In Detail
๐ค AIAnomalyDetector
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
๐ก๏ธ AIRequestValidator
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
โฑ๏ธ RateLimiter
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
๐ WatchLog
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 |
๐ analyse_logs
Reads yesterday's logs and writes a plain English report using AI.
python manage.py analyse_logs
What 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_logs
AI Providers
Works 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.
Complete Settings Reference
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',
],
}
Requirements
- Python 3.10+
- Django 4.2+
httpxโ installed automaticallyapschedulerโ optional, only forANALYSE_LOGS_AT
Known Limitations
| 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 |
Roadmap
- Usage dashboard at
/smart-layer/usage/ - Grey-zone AI analysis in
AIAnomalyDetector - Email delivery for daily reports
- Test suite
License
MIT โ free to use, modify, and distribute.
Built for Django developers who want real protection without the complexity.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file django_smart_layer-0.1.1.tar.gz.
File metadata
- Download URL: django_smart_layer-0.1.1.tar.gz
- Upload date:
- Size: 19.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
93a110df9ad7ec56d7a959f96258d7df4261fc6b06561ebb55e2d110662cc796
|
|
| MD5 |
72668ed6686e229d71bd79d8eba2b673
|
|
| BLAKE2b-256 |
9db69e97a805e8087b2425c64d2055ed9bb9078b2ed091277d68a9b62848d528
|
File details
Details for the file django_smart_layer-0.1.1-py3-none-any.whl.
File metadata
- Download URL: django_smart_layer-0.1.1-py3-none-any.whl
- Upload date:
- Size: 23.4 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.12.10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1ef6817b8bc839a805e0fbdfd333a92d7eb5cd170588af5c6f0ebdd27d75ca70
|
|
| MD5 |
e8ad9a01b8eb7b92cf614d7394b2f164
|
|
| BLAKE2b-256 |
196eacd0853313996b2808dc7530bb2848000a8cfb54c12b0742b692b967a4d6
|