Coverage for src/couchers/helpers/geoip.py: 27%
33 statements
« prev ^ index » next coverage.py v7.6.10, created at 2025-06-01 15:07 +0000
« prev ^ index » next coverage.py v7.6.10, created at 2025-06-01 15:07 +0000
1import logging
3import geoip2.database
4from geoip2.errors import AddressNotFoundError
6from couchers.config import config
8logger = logging.getLogger(__name__)
11def geoip_approximate_location(ip_address: str) -> str | None:
12 if config["GEOLITE2_CITY_MMDB_FILE_LOCATION"] == "":
13 return
14 if ip_address is None:
15 return
16 try:
17 with geoip2.database.Reader(config["GEOLITE2_CITY_MMDB_FILE_LOCATION"]) as reader:
18 response = reader.city(ip_address)
19 city = response.city.name
20 country = response.country.name
21 return f"{city}, {country}" if city else f"{country}"
22 except AddressNotFoundError:
23 pass
24 except Exception as e:
25 logger.error(f"GeoIP failed for {ip_address=}")
28def geoip_asn(ip_address: str) -> tuple[int, str, str] | None:
29 if config["GEOLITE2_ASN_MMDB_FILE_LOCATION"] == "":
30 return
31 if ip_address is None:
32 return
33 try:
34 with geoip2.database.Reader(config["GEOLITE2_ASN_MMDB_FILE_LOCATION"]) as reader:
35 response = reader.asn(ip_address)
36 return response.autonomous_system_number, response.autonomous_system_organization, response.network
37 except AddressNotFoundError:
38 pass
39 except Exception as e:
40 logger.error(f"GeoIP failed for {ip_address=}")