Wednesday, September 25, 2013

Supporting IP address ranges in Django Internal IPs setting

Django internal ips is one of those pesky little details that turn out to be the reason for your css not loading in your web app after you restarted your machine. Here is the chain of events:

Restart -> DHCP -> IP change -> no longer an internal IP -> DEBUG is false -> your templates render as if on production -> you need css instead of less.

Unfortunately internal_ips can only take individual IP addresses and not a range. So if you decide to package your app into a nice vagrant VM for distributing to your colleagues, when they run and try to access it, again the same problem.

Solution is simple. After all it is Python we are talking about. :)

Inspired by http://dancarroll.org/blog/2011/01/debugging-django-dev-server/, I included a container derived from list that answers yes to the membership question whenever the given key matches one of the patterns in the list.

from fnmatch import fnmatch
class globlist(list):
    def __contains__(self, key):
        for pat in self:
            if fnmatch(key, pat): return True
        return False
# Put the whole internal range as internal ips
INTERNAL_IPS = globlist(['127.0.0.1','192.168.1.*'])

Voila!