| 49 | |
| 50 | |
| 51 | class GeoIP2: |
| 52 | # The flags for GeoIP memory caching. |
| 53 | # Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order. |
| 54 | MODE_AUTO = 0 |
| 55 | # Use the C extension with memory map. |
| 56 | MODE_MMAP_EXT = 1 |
| 57 | # Read from memory map. Pure Python. |
| 58 | MODE_MMAP = 2 |
| 59 | # Read database as standard file. Pure Python. |
| 60 | MODE_FILE = 4 |
| 61 | # Load database into memory. Pure Python. |
| 62 | MODE_MEMORY = 8 |
| 63 | cache_options = frozenset( |
| 64 | (MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, MODE_MEMORY) |
| 65 | ) |
| 66 | |
| 67 | _path = None |
| 68 | _reader = None |
| 69 | |
| 70 | def __init__(self, path=None, cache=0, country=None, city=None): |
| 71 | """ |
| 72 | Initialize the GeoIP object. No parameters are required to use default |
| 73 | settings. Keyword arguments may be passed in to customize the locations |
| 74 | of the GeoIP datasets. |
| 75 | |
| 76 | * path: Base directory to where GeoIP data is located or the full path |
| 77 | to where the city or country data files (*.mmdb) are located. |
| 78 | Assumes that both the city and country data sets are located in |
| 79 | this directory; overrides the GEOIP_PATH setting. |
| 80 | |
| 81 | * cache: The cache settings when opening up the GeoIP datasets. May be |
| 82 | an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO, |
| 83 | MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY, |
| 84 | `GeoIPOptions` C API settings, respectively. Defaults to 0, |
| 85 | meaning MODE_AUTO. |
| 86 | |
| 87 | * country: The name of the GeoIP country data file. Defaults to |
| 88 | 'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting. |
| 89 | |
| 90 | * city: The name of the GeoIP city data file. Defaults to |
| 91 | 'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting. |
| 92 | """ |
| 93 | if cache not in self.cache_options: |
| 94 | raise GeoIP2Exception("Invalid GeoIP caching option: %s" % cache) |
| 95 | |
| 96 | path = path or getattr(settings, "GEOIP_PATH", None) |
| 97 | city = city or getattr(settings, "GEOIP_CITY", "GeoLite2-City.mmdb") |
| 98 | country = country or getattr(settings, "GEOIP_COUNTRY", "GeoLite2-Country.mmdb") |
| 99 | |
| 100 | if not path: |
| 101 | raise GeoIP2Exception( |
| 102 | "GeoIP path must be provided via parameter or the GEOIP_PATH setting." |
| 103 | ) |
| 104 | |
| 105 | path = to_path(path) |
| 106 | |
| 107 | # Try the path first in case it is the full path to a database. |
| 108 | for path in (path, path / city, path / country): |
no outgoing calls