Package: django-blacklist
Django BlacklistBlacklist users and hosts in Django. Automatically blacklist rate-limited clients.OverviewDjango Blacklistallows you to block specific users and IP addresses/networks from accessing your application.
Clients can be blocked manually from the admin interface, or automatically after exceeding a request rate limit.
Each blacklist rule is applied for a specific duration.
The blacklist is very scalable and is applied without noticeable overhead for large numbers of rules.InstallationTo install the package, run:$ pip install django-blacklistAdd theblacklistapplication toINSTALLED_APPS:INSTALLED_APPS = [
    ...
    'blacklist'
]Add theBlacklistMiddlewaremiddleware afterAuthenticationMiddleware:MIDDLEWARE = [
    ...
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'blacklist.middleware.BlacklistMiddleware',
    ...
]Apply the blacklist database migrations:$ python manage.py migrate blacklistUsageYou can manage the blacklist rules from the admin.
Changes take effect after a configurable time, or when the server is restarted.
A rule can target a user or an IP address.
You can also target IP networks (ranges) by specifying the optionalprefixlenfield (number of network prefix bits).
Each rule has a specific duration. After that time interval passes, the rule expires.
When a request is blocked due to a matching rule:Status 400 (bad request) is returned.An error template is rendered.
You can specify a custom one (seeSettingsbelow), or use the one for status 400.A message is logged
(warning from loggerblacklist.middlewarefor custom templates, or error from loggerdjango.securityotherwise).Removing Expired RulesExpired rules are not automatically removed from the database.
They can be cleaned up with the included management commandtrim_blacklist:$ python manage.py trim_blacklist [-c <created_days>] [-e <expired_days>]The options-cand-especify the minimum ages of creation and expiry, respectively.Automatic BlacklistingClients can be blacklisted automatically, after exceeding a specified request rate limit.
This feature requiresdjango-ratelimit.First, rate-limit a view by applying the@ratelimitdecorator. Make sure to setblock=False.
Then, blacklist rate-limited clients by adding the@blacklist_ratelimiteddecorator. Specify the blacklist duration.
For example:from datetime import timedelta
from django_ratelimit.decorators import ratelimit
from blacklist.ratelimit import blacklist_ratelimited

@ratelimit(key='user_or_ip', rate='50/m', block=False)
@blacklist_ratelimited(timedelta(minutes=30))
def index(request):
    ...Automatic rules take effect immediately.
If the request comes from an authenticated user, the rule will target that user.
Otherwise, it will target their IP address.@blacklist_ratelimitedaccepts two arguments:(duration, block=True).durationcan be atimedeltaobject, or a tuple of two separate durations
(for user-based and IP-based rules).blockspecifies if the request should be blocked immediately, or passed to the view.Automatic rules will have a comment that contains the ID of the request, which triggered the creation of the rule,
and the "request line".
The request ID is added only if available. Django does not generate request IDs.
For that purpose, you can installdjango-log-request-id.Proxies and Client AddressesBy default, the client IP address is taken from theREMOTE_ADDRvalue ofrequest.META.
If your application server is behind one or more reverse proxies,
this will usually be the address of the nearest proxy, and not the actual client address.
To properly blacklist clients by IP address,
you can configureDjango Blacklistto use addresses from another source (seeSettingsbelow).To actually obtain the proxied client addresses,
you can usedjango-ipware.
In this case, you can configureDjango Blacklistto obtain client addresses from your function,
which in turn callsdjango-ipwarefor the actual logic.Alternatively, you can setREMOTE_ADDRfrom theX-Forwarded-Forheader in middleware,
installed beforeDjango Blacklist.
However, keep in mind that this header can be forged to bypass the rate limits.
To counter that, you can use the last address in that header (which should be set by your trusted reverse proxy).
If you are behind two proxies, use the second to last address, and so on.SettingsBLACKLIST_ENABLE- whether blacklisted clients should be blocked,
and rate-limited clients should be blacklisted; default:TrueBLACKLIST_RELOAD_PERIOD- how often to reload the blacklist, in seconds; default:60BLACKLIST_RATELIMITED_ENABLE- whether rate-limited clients should be automatically blacklisted;
requiresBLACKLIST_ENABLE; default:TrueBLACKLIST_TEMPLATE- name of a custom error template to render to blocked clients;
its context will containrequestandexception;
set toNoneto use the template for status 400; default:NoneBLACKLIST_LOGGING_ENABLE- whether blocked requests should be logged
(honored only if a custom error template is configured); default:TrueBLACKLIST_ADDRESS_SOURCE- the source of client addresses; can be a key inrequest.META,
a callable that receives the request object, or the dotted string path to such a callable;
default:'REMOTE_ADDR'