Login

Include entire networks in INTERNAL_IPS setting

Author:
pmclanahan
Posted:
March 10, 2009
Language:
Python
Version:
1.0
Score:
4 (after 4 ratings)

A simple addition to the settings.py file of your project to allow you to easily specify entire network ranges as internal. This is especially useful in conjunction with other tools such as the Django Debug Toolbar.

After you set this up, the following test should pass

test_str = """
>>> '192.168.1.5' in INTERNAL_IPS
True
>>> '192.168.3.5' in INTERNAL_IPS
FALSE
"""

Requirements

Acknowledgements

Jeremy Dunck: The initial code for this idea is by Jeremy and in Django ticket #3237. I just changed the module and altered the use of the list superclass slightly. I mainly wanted to put the code here for safe keeping. Thanks Jeremy!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class IPList(list):

    def __init__(self, ips):
        try:
            #http://software.inl.fr/trac/wiki/IPy
            #ubuntu: apt-get install python-ipy
            from IPy import IP
            for ip in ips:
                self.append(IP(ip))
        except ImportError:
            pass
            
    def __contains__(self, ip):
        try:
            for net in self:
                if ip in net:
                    return True
        except:
            pass
        return False
            
INTERNAL_IPS = IPList(['127.0.0.1', '192.168.1.0/24'])

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

pmclanahan (on October 14, 2009):

kcarnold: That one is excellent for the most common case. I'll be using it. Thanks for the tip!

#

Please login first before commenting.