First Steps¶
Let's start with a simple example that shows how to add DjangoAPI Guard to your application.
Create a Django application¶
First, create a new Django project:
Configure Security Settings¶
Create a SecurityConfig instance in your Django settings:
# settings.py
GUARD_SECURITY_CONFIG = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"), # NOTE: Required for geolocation
enable_redis=True, # Enable Redis integration
redis_url="redis://localhost:6379", # Redis URL
rate_limit=100, # Max requests per minute
auto_ban_threshold=5, # Ban after 5 suspicious requests
custom_log_file="security.log" # Custom log file
)
Note: DjangoAPI Guard only loads resources as needed. The IPInfo database is only downloaded when country filtering is configured, and cloud IP ranges are only fetched when cloud provider blocking is enabled.
Add the Middleware¶
Add the security middleware to your Django MIDDLEWARE setting:
# settings.py
MIDDLEWARE = [
"djangoapi_guard.middleware.DjangoAPIGuard",
"django.middleware.common.CommonMiddleware",
# ... other middleware
]
Complete Example¶
Here's a complete example showing basic usage:
# settings.py
from djangoapi_guard import SecurityConfig
from djangoapi_guard import IPInfoManager
GUARD_SECURITY_CONFIG = SecurityConfig(
geo_ip_handler=IPInfoManager("your_ipinfo_token_here"),
enable_redis=True, # Redis enabled
redis_url="redis://localhost:6379",
whitelist=["192.168.1.1", "2001:db8::1"],
blacklist=["10.0.0.1", "2001:db8::2"],
blocked_countries=["AR", "IT"],
rate_limit=100,
custom_log_file="security.log"
)
MIDDLEWARE = [
"djangoapi_guard.middleware.DjangoAPIGuard",
"django.middleware.common.CommonMiddleware",
# ...
]
# views.py
from django.http import JsonResponse
def root(request):
return JsonResponse({"message": "Hello World"})
Run the Application¶
Run your application using gunicorn:
Your API is now protected by DjangoAPI Guard!
What's Next¶
- Learn about IP Management
- Configure Rate Limiting
- Set up Penetration Detection
- Learn about Redis Integration