Coverage for src/couchers/helpers/geoip.py: 40%

20 statements  

« prev     ^ index     » next       coverage.py v7.5.0, created at 2024-12-20 18:03 +0000

1import logging 

2 

3import geoip2.database 

4from geoip2.errors import AddressNotFoundError 

5 

6from couchers.config import config 

7 

8logger = logging.getLogger(__name__) 

9 

10 

11def geoip_approximate_location(ip_address: str) -> str: 

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=}")