Home > Programming & scripting, Python > Simplified IP-ban middleware

Simplified IP-ban middleware

August 23rd, 2007

This is based on the last post where I showed a simple middleware for IP banning in django.
In the comments, SmileyChris mentioned that simply rendering the template in the middleware would eliminate the need for a url configuration and view for the IP ban middleware. This was actually a really great idea, since it also removes the need to check the path for the ban page, and everything becomes a lot cleaner. Thanks :)

I rewrote the middleware to use this method instead, and it now looks like this

from pici.picipage.models import Ban
from django.shortcuts import render_to_response

class IPBanMiddleware(object):
  """
  Simple middleware for taking care of bans from specific IP's
  Redirects the banned user to a ban-page with an explanation
  """
  def process_request(self, request):
    ip = request.META['REMOTE_ADDR'] # user's IP

    # see if user is banned
    try:
      # if this doesnt throw an exception, user is banned
      ban = Ban.objects.get(ip=ip)
      reason = ban.reason

      # return the "ban page"
      return render_to_response("subpages/banned/banned.html",
        {"reason": reason})
    except Ban.DoesNotExist: # not banned! goodie
      pass

No additional view or url-patterns needed, simply add the Ban model that I wrote in the last post into your model, and create the template and you are good to go!

My Ban model looked like this (same as last post), but can of course be improved to fit your needs.

class Ban(models.Model):
    ip = models.IPAddressField()
    reason = models.TextField()

    def __str__(self):
        return self.ip

    class Admin: pass

Thanks for the idea, and I hope that other people will start “bashing my code” as well ;)
Constructive criticism is an awesome thing, and I know that there are a whole lot of more experienced django developers than me out there.

buffi Programming & scripting, Python

  1. May 13th, 2008 at 14:31 | #1

    Simple but powerful way to ban IPs. Thanks for the code. :)

  1. August 30th, 2007 at 00:17 | #1