Login

CIDR compatible INTERNAL_IPS with Python 3 Standard Library

Author:
yklim
Posted:
January 27, 2018
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

use only in a dev environment.

  • requirement: Python 3.3+
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from collections import Iterable
from ipaddress import IPv4Address, IPv4Network

class IpList(object):
    def __init__(self, addresses):
        self.addresses = [IPv4Network(address) if isinstance(address, Iterable) else IPv4Address(address) for address in addresses]

    def __contains__(self, ip):
        ip = IPv4Address(ip)
        for address in self.addresses:
            if isinstance(address, IPv4Address):
                if ip == address:
                    return True
            if isinstance(address, IPv4Network):
                if ip in address:
                    return True
        return False

INTERNAL_IPS = IpList([
    '127.0.0.1',
    '192.168.0.0/24'
    ])

More like this

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

Comments

Please login first before commenting.