geoobjects / geoobjects /

# -*- encoding: utf-8 -*-
import struct
import socket
from django.db import models
from django.core.exceptions import ObjectDoesNotExist
from django.core.cache import cache
from django.core.exceptions import FieldError
from django.utils.functional import cached_property

__author__ = 'vadim'

DELIM = ':'


class GeobazaRanges(models.Model):
    start = models.CharField(max_length=15)
    end = models.CharField(max_length=15)
    ip_int = models.BigIntegerField()
    length = models.BigIntegerField()
    tld = models.CharField(max_length=4, null=True)
    obj_id = models.PositiveIntegerField(max_length=11)

    class Meta:
        unique_together = ('ip_int', 'length')

    def __unicode__(self):
        return u"%s-%s" % (self.start, self.end)

    def get_obj(cls, ip):
        int_ip = struct.unpack('>L', socket.inet_aton(ip))[0]
        key_cache = "geo_range_" + str(ip)
        ob = cache.get(key_cache)
        if ob is None:
                ob = cls.objects.all().extra(where=['ip_int <= %d AND ip_int + length >=%d' % (int_ip, int_ip)],
                cache.set(key_cache, ob)
            except ObjectDoesNotExist:
                ob = None
        return ob

    def obj(self):
        key_cache = "geo_obj_" + str(self.obj_id)
        ob = cache.get(key_cache)
        if ob is None:
                ob = GeobazaObjects.objects.get(pk=self.obj_id)
            except ObjectDoesNotExist:
                ob = GeobazaObjects.objects.get(pk=DEFAULT_GEO_LOCATION)
            cache.set(key_cache, ob)
        return ob

class GeobazaObjects(models.Model):
    parent_id = models.PositiveIntegerField()
    type = models.CharField(max_length=100)
    name_en = models.CharField(max_length=255)
    name_ru = models.CharField(max_length=255, null=True, default=None)
    lat = models.FloatField(null=True, default=None)
    lon = models.FloatField(null=True, default=None)

    def __unicode__(self):
        return u"%s:%s" % (self.type, self.name_en)

    def get_obj(cls, obj_id):
        key_cache = "geo_obj_%d" % obj_id
        ob = cache.get(key_cache)
        if ob is None:
            ob = GeobazaObjects.objects.get(pk=obj_id)
            cache.set(key_cache, ob)
        return ob

    def parent(self):
            return GeobazaObjects.objects.get(pk=self.parent_id)
        except ObjectDoesNotExist:
            return None

    def child(self):
        return GeobazaObjects.objects.all().filter(

    def get_path(self, reverse=False):
        path = [self]
        parent = self.parent
        while parent:
            parent = parent.parent
        if reverse:
        return path

    def to_dict(self, lang='ru'):
        return {}

    def path(self):
        return self.get_path()

    def country(self):
        for obj in self.path:
            if obj.type == 'country':
                return obj
        return None

    def name(self, lang='en'):
        return u', '.join([path.name_ru if lang == 'ru' and path.name_ru else path.name_en
                           for path in self.get_path(False)])

    def dump_path(self):
        path = self.path
        if not path:  # or (hasattr(path, 'is_special') and path.is_special):
            return ''
        ret = DELIM.join([str( for obj in path])
        return DELIM + ret + DELIM

    def dump_key(self):
        return DELIM + str( + DELIM

class GeoField(models.CharField):
    __metaclass__ = models.SubfieldBase
    description = "Stores GEO data"

    def __init__(self, *args, **kwargs):
        self.type_field = kwargs.get('type', list)  # list (default) or dict
        super(GeoField, self).__init__(*args, **kwargs)

    def get_prep_value(self, value):
        if value is None:
            return None
        if isinstance(value, (list, tuple)) and len(value) > 1:
            ob = GeobazaObjects.get_obj(value[0])
            value = ob.dump_path if ob else None
        elif isinstance(value, dict) and len(value):
            ob = GeobazaObjects.get_obj(value.keys()[0])
            value = ob.dump_path if ob else None
        elif isinstance(value, int):
            ob = GeobazaObjects.get_obj(value)
            value = ob.dump_path if ob else None
        elif isinstance(value, basestring) and DELIM in value:
            raise FieldError('GeoField take value type=%s. Only dict, int, path support!' % type(value))

        return value

    def to_python(self, value):
        if isinstance(value, basestring) and len(value):
                val = int(value.split(DELIM)[1]) if DELIM in value else int(value)
                ob = GeobazaObjects.get_obj(val)
                if ob:
                    value = ob.to_dict()
                    if self.type_field == list:
                        value = value.items()[0]
        return value

    def south_field_triple(self):
        """Returns a suitable description of this field for South."""
        # We'll just introspect the _actual_ field.
            from south.modelsinspector import introspector
            field_class = self.__class__.__module__ + "." + self.__class__.__name__
            args, kwargs = introspector(self)
            # That's our definition!
            return field_class, args, kwargs