import netaddr
from mongoengine import *

class IPNetwork(Document):
    """
    Represents an IP (v4 or v6) network as 2 integers, the starting address and the stopping address, inclusive.
    """
    label = StringField(required=False)
    start = IntField(required=True)
    stop = IntField(required=True)
    whitelist = BooleanField(default=False)

    meta = {
        'indexes': [('start', 'stop', 'whitelist')]
    }

    @classmethod
    def create_from_string(cls, cidr, label=None, whitelist=False):
        """
        Converts a CIDR like 192.168.0.0/24 into 2 parts:
            start: 3232235520
            stop: 3232235775
        """
        network = netaddr.IPNetwork(cidr)
        start = network.first
        stop = start + network.size - 1
        obj = cls.objects.create(label=label, start=start, stop=stop, whitelist=whitelist)
        return obj

    def __unicode__(self):
        return "%s: %s - %s" % (self.label, str(netaddr.IPAddress(self.start)), str(netaddr.IPAddress(self.stop)))

    @classmethod
    def matches_ip(cls, ip_str):
        ip = int(netaddr.IPAddress(ip_str))
        return (cls.objects.filter(start__lte=ip, stop__gte=ip, whitelist=False).count() > 0) \
                and not (cls.objects.filter(start__lte=ip, stop__gte=ip, whitelist=True).count() > 0)

@@ -1073,136 +1073,377 @@
     
-ip = int(netaddr.IPAddress(ip_str))%0A        return (cls.objects.filter(start__lte=ip, stop__gte=ip, whitelist=False).count() %3E 0
+%22%22%22%0A        Return True if provided IP exists in the blacklist and doesn't exist%0A        in the whitelist. Otherwise, return False.%0A        %22%22%22%0A        ip = int(netaddr.IPAddress(ip_str))%0A        ip_range_query = %7B%0A            'start__lte': ip,%0A            'stop__gte': ip%0A        %7D%0A        return cls.objects.filter(whitelist=False, **ip_range_query).only('id').first(
 ) %5C%0A
@@ -1466,17 +1466,16 @@
 and not 
-(
 cls.obje
@@ -1489,62 +1489,57 @@
 ter(
-start__lte=ip, stop__gte=ip, whitelist=True).count() %3E 0
+whitelist=True, **ip_range_query).only('id').first(
 )%0A

make matches_ip faster + docstring