Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reject a request prematurely with django?

I'm getting a lot of spambot requests (requests with referrer as a spam site). How do I reject a request prematurely with process_request on middleware so that django simply don't respond to the requests made from a specific referrer?

like image 474
All Іѕ Vаиітy Avatar asked Dec 05 '22 21:12

All Іѕ Vаиітy


1 Answers

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    

class RejectSpambotRequestsMiddleware(object):  

    def process_request(self, request):  
        referer = request.META.get('HTTP_REFERER')
        if referer == 'spambot_site_referer':
            return HttpResponseForbidden() # reject the request and return 403 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.

like image 148
Rahul Gupta Avatar answered Dec 20 '22 15:12

Rahul Gupta