How to ignore exceptions raised by a specific middleware

Our app supports arbitrary domains, which means ALLOWED_HOSTS = ['*'] but we handle them manually with a custom middleware:

class AllowedHostMiddleware(object):
    def process_request(self, request):
        if not domain_allowed(request.get_host()):
            raise DisallowedDomain('Invalid domain: {}.format(domain')


  • a giant log file is being created because it’s logging every random host on the web, basically crawlers

  • custom error handling middleware doesn’t work because it works only with exceptions thrown by views, not by other middleware.

My understanding is that the way ALLOWED_HOSTS work natively is that is just eats disallowed requests and doesn’t log them.

  • How can I do the same with my own middleware? Or how can I handle DisallowedDomain exceptions and route them to a different log?

  • The middleware should block the request but it shouldn’t treat it as an error otherwise it’s going to get logged, pollute the log files and contribute to their massive size.

I’m on Django 1.8.

A couple ideas come to mind off the top of my head.

  1. Instead of raising an exception in your process_request, return an HttpResponse. That short-circuits the rest of the call cycle and returns whatever you supply at that point.

  2. Change your logger handler to write logs from this class to /dev/null (or, if you want some record of this, to a rotating file handler with a small number of small files).


That was a good suggestion. I’ll take that approach. Thank you very much!