Debian Codegraph @

django/contrib/gis/geoip2.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 This module houses the GeoIP2 object, a wrapper for the MaxMind GeoIP2(R)
3 Python API (https://geoip2.readthedocs.io/). This is an alternative to the
4 Python GeoIP2 interface provided by MaxMind.
5
6 GeoIP(R) is a registered trademark of MaxMind, Inc.
7
8 For IP-based geolocation, this module requires the GeoLite2 Country and City
9 datasets, in binary format (CSV will not work!). The datasets may be
10 downloaded from MaxMind at https://dev.maxmind.com/geoip/geoip2/geolite2/.
11 Grab GeoLite2-Country.mmdb.gz and GeoLite2-City.mmdb.gz, and unzip them in the
12 directory corresponding to settings.GEOIP_PATH.
13 """
14
15 import ipaddress
16 import socket
17 import warnings
18
19 from django.conf import settings
20 from django.core.exceptions import ValidationError
21 from django.core.validators import validate_ipv46_address
22 from django.utils._os import to_path
23 from django.utils.deprecation import RemovedInDjango60Warning
24 from django.utils.functional import cached_property
25
26 __all__ = ["HAS_GEOIP2"]
27
28 try:
29 import geoip2.database
30 except ImportError: # pragma: no cover
31 HAS_GEOIP2 = False
32 else:
33 HAS_GEOIP2 = True
34 __all__ += ["GeoIP2", "GeoIP2Exception"]
35
36
37 # These are the values stored in the `database_type` field of the metadata.
38 # See https://maxmind.github.io/MaxMind-DB/#database_type for details.
39 SUPPORTED_DATABASE_TYPES = {
40 "DBIP-City-Lite",
41 "DBIP-Country-Lite",
42 "GeoIP2-City",
43 "GeoIP2-Country",
44 "GeoLite2-City",
45 "GeoLite2-Country",
46 }
47
48
49 class GeoIP2Exception(Exception):
50 pass
51
52
53 class GeoIP2:
54 # The flags for GeoIP memory caching.
55 # Try MODE_MMAP_EXT, MODE_MMAP, MODE_FILE in that order.
56 MODE_AUTO = 0
57 # Use the C extension with memory map.
58 MODE_MMAP_EXT = 1
59 # Read from memory map. Pure Python.
60 MODE_MMAP = 2
61 # Read database as standard file. Pure Python.
62 MODE_FILE = 4
63 # Load database into memory. Pure Python.
64 MODE_MEMORY = 8
65 cache_options = frozenset(
66 (MODE_AUTO, MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, MODE_MEMORY)
67 )
68
69 _path = None
70 _reader = None
71
72 def __init__(self, path=None, cache=0, country=None, city=None):
73 """
74 Initialize the GeoIP object. No parameters are required to use default
75 settings. Keyword arguments may be passed in to customize the locations
76 of the GeoIP datasets.
77
78 * path: Base directory to where GeoIP data is located or the full path
79 to where the city or country data files (*.mmdb) are located.
80 Assumes that both the city and country data sets are located in
81 this directory; overrides the GEOIP_PATH setting.
82
83 * cache: The cache settings when opening up the GeoIP datasets. May be
84 an integer in (0, 1, 2, 4, 8) corresponding to the MODE_AUTO,
85 MODE_MMAP_EXT, MODE_MMAP, MODE_FILE, and MODE_MEMORY,
86 `GeoIPOptions` C API settings, respectively. Defaults to 0,
87 meaning MODE_AUTO.
88
89 * country: The name of the GeoIP country data file. Defaults to
90 'GeoLite2-Country.mmdb'; overrides the GEOIP_COUNTRY setting.
91
92 * city: The name of the GeoIP city data file. Defaults to
93 'GeoLite2-City.mmdb'; overrides the GEOIP_CITY setting.
94 """
95 if cache not in self.cache_options:
96 raise GeoIP2Exception("Invalid GeoIP caching option: %s" % cache)
97
98 path = path or getattr(settings, "GEOIP_PATH", None)
99 city = city or getattr(settings, "GEOIP_CITY", "GeoLite2-City.mmdb")
100 country = country or getattr(settings, "GEOIP_COUNTRY", "GeoLite2-Country.mmdb")
101
102 if not path:
103 raise GeoIP2Exception(
104 "GeoIP path must be provided via parameter or the GEOIP_PATH setting."
105 )
106
107 path = to_path(path)
108
109 # Try the path first in case it is the full path to a database.
110 for path in (path, path / city, path / country):
111 if path.is_file():
112 self._path = path
113 self._reader = geoip2.database.Reader(path, mode=cache)
114 break
115 else:
116 raise GeoIP2Exception(
117 "Path must be a valid database or directory containing databases."
118 )
119
120 database_type = self._metadata.database_type
121 if database_type not in SUPPORTED_DATABASE_TYPES:
122 raise GeoIP2Exception(f"Unable to handle database edition: {database_type}")
123
124 def __del__(self):
125 # Cleanup any GeoIP file handles lying around.
126 if self._reader:
127 self._reader.close()
128
129 def __repr__(self):
130 m = self._metadata
131 version = f"v{m.binary_format_major_version}.{m.binary_format_minor_version}"
132 return f"<{self.__class__.__name__} [{version}] _path='{self._path}'>"
133
134 @cached_property
135 def _metadata(self):
136 return self._reader.metadata()
137
138 @cached_property
139 def is_city(self):
140 return "City" in self._metadata.database_type
141
142 @cached_property
143 def is_country(self):
144 return "Country" in self._metadata.database_type
145
146 def _query(self, query, *, require_city=False):
147 if not isinstance(query, (str, ipaddress.IPv4Address, ipaddress.IPv6Address)):
148 raise TypeError(
149 "GeoIP query must be a string or instance of IPv4Address or "
150 "IPv6Address, not type %s" % type(query).__name__,
151 )
152
153 if require_city and not self.is_city:
154 raise GeoIP2Exception(f"Invalid GeoIP city data file: {self._path}")
155
156 if isinstance(query, str):
157 try:
158 validate_ipv46_address(query)
159 except ValidationError:
160 # GeoIP2 only takes IP addresses, so try to resolve a hostname.
161 query = socket.gethostbyname(query)
162
163 function = self._reader.city if self.is_city else self._reader.country
164 return function(query)
165
166 def city(self, query):
167 """
168 Return a dictionary of city information for the given IP address or
169 Fully Qualified Domain Name (FQDN). Some information in the dictionary
170 may be undefined (None).
171 """
172 response = self._query(query, require_city=True)
173 region = response.subdivisions[0] if response.subdivisions else None
174 return {
175 "accuracy_radius": response.location.accuracy_radius,
176 "city": response.city.name,
177 "continent_code": response.continent.code,
178 "continent_name": response.continent.name,
179 "country_code": response.country.iso_code,
180 "country_name": response.country.name,
181 "is_in_european_union": response.country.is_in_european_union,
182 "latitude": response.location.latitude,
183 "longitude": response.location.longitude,
184 "metro_code": response.location.metro_code,
185 "postal_code": response.postal.code,
186 "region_code": region.iso_code if region else None,
187 "region_name": region.name if region else None,
188 "time_zone": response.location.time_zone,
189 # Kept for backward compatibility.
190 "dma_code": response.location.metro_code,
191 "region": region.iso_code if region else None,
192 }
193
194 def country_code(self, query):
195 "Return the country code for the given IP Address or FQDN."
196 return self.country(query)["country_code"]
197
198 def country_name(self, query):
199 "Return the country name for the given IP Address or FQDN."
200 return self.country(query)["country_name"]
201
202 def country(self, query):
203 """
204 Return a dictionary with the country code and name when given an
205 IP address or a Fully Qualified Domain Name (FQDN). For example, both
206 '24.124.1.80' and 'djangoproject.com' are valid parameters.
207 """
208 response = self._query(query, require_city=False)
209 return {
210 "continent_code": response.continent.code,
211 "continent_name": response.continent.name,
212 "country_code": response.country.iso_code,
213 "country_name": response.country.name,
214 "is_in_european_union": response.country.is_in_european_union,
215 }
216
217 def coords(self, query, ordering=("longitude", "latitude")):
218 warnings.warn(
219 "GeoIP2.coords() is deprecated. Use GeoIP2.lon_lat() instead.",
220 RemovedInDjango60Warning,
221 stacklevel=2,
222 )
223 data = self.city(query)
224 return tuple(data[o] for o in ordering)
225
226 def lon_lat(self, query):
227 "Return a tuple of the (longitude, latitude) for the given query."
228 data = self.city(query)
229 return data["longitude"], data["latitude"]
230
231 def lat_lon(self, query):
232 "Return a tuple of the (latitude, longitude) for the given query."
233 data = self.city(query)
234 return data["latitude"], data["longitude"]
235
236 def geos(self, query):
237 "Return a GEOS Point object for the given query."
238 # Allows importing and using GeoIP2() when GEOS is not installed.
239 from django.contrib.gis.geos import Point
240
241 return Point(self.lon_lat(query), srid=4326)
242
243 @classmethod
244 def open(cls, full_path, cache):
245 warnings.warn(
246 "GeoIP2.open() is deprecated. Use GeoIP2() instead.",
247 RemovedInDjango60Warning,
248 stacklevel=2,
249 )
250 return GeoIP2(full_path, cache)