creating the settings dictionary with any settings if needed the flags for geoip memory caching try modemmapext modemmap modefile in that order use the c extension with memory map read from memory map pure python read database as standard file pure python load database into memory pure python paths to the city country binary databases initially pointers to geoip file references are null initialize the geoip object no parameters are required to use default settings keyword arguments may be passed in to customize the locations of the geoip datasets path base directory to where geoip data is located or the full path to where the city or country data files mmdb are located assumes that both the city and country data sets are located in this directory overrides the geoippath setting cache the cache settings when opening up the geoip datasets may be an integer in 0 1 2 4 8 corresponding to the modeauto modemmapext modemmap modefile and modememory geoipoptions c api settings respectively defaults to 0 meaning modeauto country the name of the geoip country data file defaults to geolite2country mmdb overrides the geoipcountry setting city the name of the geoip city data file defaults to geolite2city mmdb overrides the geoipcity setting checking the given cache option getting the geoip data path constructing the geoip database filenames using the settings dictionary if the database files for the geolite country andor city datasets exist then try to open them otherwise some detective work will be needed to figure out whether the given database path is for the geoip country or city databases geolite city database detected geoip country database detected cleanup any geoip file handles lying around making sure a string was passed in for the query extra checks for the existence of country and city databases return the query string back to the caller geoip2 only takes ip addresses return a dictionary of city information for the given ip address or fully qualified domain name fqdn some information in the dictionary may be undefined none return a dictionary with the country code and name when given an ip address or a fully qualified domain name fqdn for example both 24 124 1 80 and djangoproject com are valid parameters returning the country code and name allows importing and using geoip2 when geos is not installed creating the settings dictionary with any settings if needed the flags for geoip memory caching try mode_mmap_ext mode_mmap mode_file in that order use the c extension with memory map read from memory map pure python read database as standard file pure python load database into memory pure python paths to the city country binary databases initially pointers to geoip file references are null initialize the geoip object no parameters are required to use default settings keyword arguments may be passed in to customize the locations of the geoip datasets path base directory to where geoip data is located or the full path to where the city or country data files mmdb are located assumes that both the city and country data sets are located in this directory overrides the geoip_path setting cache the cache settings when opening up the geoip datasets may be an integer in 0 1 2 4 8 corresponding to the mode_auto mode_mmap_ext mode_mmap mode_file and mode_memory geoipoptions c api settings respectively defaults to 0 meaning mode_auto country the name of the geoip country data file defaults to geolite2 country mmdb overrides the geoip_country setting city the name of the geoip city data file defaults to geolite2 city mmdb overrides the geoip_city setting checking the given cache option getting the geoip data path constructing the geoip database filenames using the settings dictionary if the database files for the geolite country and or city datasets exist then try to open them otherwise some detective work will be needed to figure out whether the given database path is for the geoip country or city databases geolite city database detected geoip country database detected cleanup any geoip file handles lying around making sure a string was passed in for the query extra checks for the existence of country and city databases return the query string back to the caller geoip2 only takes ip addresses return a dictionary of city information for the given ip address or fully qualified domain name fqdn some information in the dictionary may be undefined none return a dictionary with the country code and name when given an ip address or a fully qualified domain name fqdn for example both 24 124 1 80 and djangoproject com are valid parameters returning the country code and name allows importing and using geoip2 when geos is not installed
import socket
import warnings

import geoip2.database

from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_ipv46_address
from django.utils._os import to_path
from django.utils.deprecation import RemovedInDjango60Warning

from .resources import City, Country


GEOIP_SETTINGS = {
    "GEOIP_PATH": getattr(settings, "GEOIP_PATH", None),
    "GEOIP_CITY": getattr(settings, "GEOIP_CITY", "GeoLite2-City.mmdb"),
    "GEOIP_COUNTRY": getattr(settings, "GEOIP_COUNTRY", "GeoLite2-Country.mmdb"),
}


class GeoIP2Exception(Exception):
    pass


class GeoIP2:
    
    
    MODE_AUTO = 0
    
    MODE_MMAP_EXT = 1
    
    MODE_MMAP = 2
    
    MODE_FILE = 4
    
    MODE_MEMORY = 8
    cache_options = frozenset(
        (MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, MODE_MEMORY)
    )

    
    _city_file = ""
    _country_file = ""

    
    _city = None
    _country = None

    def __init__(self, path=None, cache=0, country=None, city=None):
        
        
        if cache not in self.cache_options:
            raise GeoIP2Exception("Invalid GeoIP caching option: %s" % cache)

        
        path = path or GEOIP_SETTINGS["GEOIP_PATH"]
        if not path:
            raise GeoIP2Exception(
                "GeoIP path must be provided via parameter or the GEOIP_PATH setting."
            )

        path = to_path(path)
        if path.is_dir():
            
            
            
            country_db = path / (country or GEOIP_SETTINGS["GEOIP_COUNTRY"])
            if country_db.is_file():
                self._country = geoip2.database.Reader(str(country_db), mode=cache)
                self._country_file = country_db

            city_db = path / (city or GEOIP_SETTINGS["GEOIP_CITY"])
            if city_db.is_file():
                self._city = geoip2.database.Reader(str(city_db), mode=cache)
                self._city_file = city_db
            if not self._reader:
                raise GeoIP2Exception("Could not load a database from %s." % path)
        elif path.is_file():
            
            
            
            reader = geoip2.database.Reader(str(path), mode=cache)
            db_type = reader.metadata().database_type

            if "City" in db_type:
                
                self._city = reader
                self._city_file = path
            elif "Country" in db_type:
                
                self._country = reader
                self._country_file = path
            else:
                raise GeoIP2Exception(
                    "Unable to recognize database edition: %s" % db_type
                )
        else:
            raise GeoIP2Exception("GeoIP path must be a valid file or directory.")

    @property
    def _reader(self):
        return self._country or self._city

    @property
    def _country_or_city(self):
        if self._country:
            return self._country.country
        else:
            return self._city.city

    def __del__(self):
        
        if self._city:
            self._city.close()
        if self._country:
            self._country.close()

    def __repr__(self):
        meta = self._reader.metadata()
        version = "[v%s.%s]" % (
            meta.binary_format_major_version,
            meta.binary_format_minor_version,
        )
        return (
            '<%(cls)s %(version)s _country_file="%(country)s", _city_file="%(city)s">'
            % {
                "cls": self.__class__.__name__,
                "version": version,
                "country": self._country_file,
                "city": self._city_file,
            }
        )

    def _check_query(self, query, city=False, city_or_country=False):
        "Check the query and database availability."
        
        if not isinstance(query, str):
            raise TypeError(
                "GeoIP query must be a string, not type %s" % type(query).__name__
            )

        
        if city_or_country and not (self._country or self._city):
            raise GeoIP2Exception("Invalid GeoIP country and city data files.")
        elif city and not self._city:
            raise GeoIP2Exception("Invalid GeoIP city data file: %s" % self._city_file)

        
        try:
            validate_ipv46_address(query)
        except ValidationError:
            query = socket.gethostbyname(query)

        return query

    def city(self, query):
        
        enc_query = self._check_query(query, city=True)
        return City(self._city.city(enc_query))

    def country_code(self, query):
        "Return the country code for the given IP Address or FQDN."
        return self.country(query)["country_code"]

    def country_name(self, query):
        "Return the country name for the given IP Address or FQDN."
        return self.country(query)["country_name"]

    def country(self, query):
        
        
        enc_query = self._check_query(query, city_or_country=True)
        return Country(self._country_or_city(enc_query))

    def coords(self, query, ordering=("longitude", "latitude")):
        warnings.warn(
            "GeoIP2.coords() is deprecated. Use GeoIP2.lon_lat() instead.",
            RemovedInDjango60Warning,
            stacklevel=2,
        )
        data = self.city(query)
        return tuple(data[o] for o in ordering)

    def lon_lat(self, query):
        "Return a tuple of the (longitude, latitude) for the given query."
        data = self.city(query)
        return data["longitude"], data["latitude"]

    def lat_lon(self, query):
        "Return a tuple of the (latitude, longitude) for the given query."
        data = self.city(query)
        return data["latitude"], data["longitude"]

    def geos(self, query):
        "Return a GEOS Point object for the given query."
        
        from django.contrib.gis.geos import Point

        return Point(self.lon_lat(query), srid=4326)

    @classmethod
    def open(cls, full_path, cache):
        return GeoIP2(full_path, cache)