How Do I Reject A Request Prematurely With Django?
Solution 1:
You can create a RejectSpambotRequestsMiddleware
class which will reject the requests if the referer
of the request is from a specific referrer.
It should return either None
or an HttpResponse
object. If it returns None
, Django will continue processing this request, executing any other process_request()
middlewares, then, process_view()
middleware, and finally, the appropriate view. Normally, a 403 Forbidden
response is sent to the user if an incoming request fails the checks performed by the middleware.
from django.http import HttpResponseForbidden
classRejectSpambotRequestsMiddleware(object):
def process_request(self, request):
referer = request.META.get('HTTP_REFERER')
if referer == 'spambot_site_referer':
return HttpResponseForbidden() # reject the request and return403 forbidden response
return # return None in case of a valid request
Then add your middleware to the MIDDLEWARE_CLASSES
in your settings.py
file.
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
...
...
# your custom middleware here'my_project.middlewares.RejectSpambotRequestsMiddleware',
)
Note: Here, RejectSpambotRequestsMiddleware
will be run at the end as Django applies middleware in the order it’s defined in MIDDLEWARE_CLASSES
, top-down. You can change the order of MIDDLEWARE_CLASSES
as per your need.
Solution 2:
Added some modifications to the answer of @Rahul Gupta. Referrer is compared to a blacklist.
classRejectSpambotRequestsMiddleware(object):def__init__(self, get_response):
self.get_response = get_response
self.blacklist = ['bot1.com', 'bot2.com']
def__call__(self, request):
referer = request.META.get('HTTP_REFERER')
response = self.get_response(request)
ifnotreferer:return response
for bad inself.blacklist:if bad inreferer:return HttpResponseForbidden()
return response
Post a Comment for "How Do I Reject A Request Prematurely With Django?"