Registry / http-networking / geoip2

geoip2

JSON →
library5.2.0pypypi✓ verified 49d ago

The geoip2 Python package provides an API for both MaxMind's GeoIP2 and GeoLite2 web services and local databases. It allows developers to perform IP geolocation lookups, retrieving information such as country, city, and ASN details. The library is actively maintained, with version 5.2.0 being the latest stable release, and follows semantic versioning with a regular release cadence.

http-networkingdata
pip install geoip2
Install & Compatibility
Where this runs
tested against v5.2.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.930 runs
installs and imports cleanly · install 0.0s · import 0.164s · 30.5MB
glibc
py 3.103.930 runs
installs and imports cleanly · install 4.5s · import 0.143s · 33MB
30MB installed
● package 30MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Reader
from geoip2.database import Reader
Client
from geoip2.webservice import Client
AsyncClient
from geoip2.webservice import AsyncClient
AddressNotFoundError
from geoip2.errors import AddressNotFoundError
try: ... except AddressNotFoundError: ... (without import)
Exceptions must be explicitly imported to be caught by name.

This example demonstrates how to perform a geolocation lookup using a local GeoLite2 City database. It also includes an optional section for using the GeoIP2 Web Service, which requires a MaxMind account ID and license key. Remember to download a MaxMind database (e.g., GeoLite2-City.mmdb) and specify its path for the local database example. Reader and Client objects should be initialized once and reused for performance.

import os import geoip2.database from geoip2.errors import AddressNotFoundError # --- Using a local GeoLite2 City database --- # 1. Download GeoLite2 City database from MaxMind (requires account): # https://dev.maxmind.com/geoip/geolite2-free-geolocation-data # 2. Extract the .mmdb file (e.g., GeoLite2-City.mmdb) and place it in a known directory. database_path = os.environ.get('GEOLITE2_CITY_DB_PATH', './GeoLite2-City.mmdb') if not os.path.exists(database_path): print(f"Error: GeoLite2 City database not found at {database_path}.") print("Please download it from MaxMind and update GEOLITE2_CITY_DB_PATH environment variable or file path.") else: try: # Reader objects are expensive to create and should be reused across lookups. with geoip2.database.Reader(database_path) as reader: ip_address = '8.8.8.8' try: response = reader.city(ip_address) print(f"IP: {ip_address}") print(f" Country: {response.country.name} ({response.country.iso_code})") print(f" City: {response.city.name}") print(f" Location: Latitude {response.location.latitude}, Longitude {response.location.longitude}") except AddressNotFoundError: print(f"IP address {ip_address} not found in the database.") except Exception as e: print(f"An error occurred during lookup for {ip_address}: {e}") # --- Using the GeoIP2 Web Service (requires MaxMind Account ID and License Key) --- # MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY should be set as environment variables account_id = os.environ.get('MAXMIND_ACCOUNT_ID') license_key = os.environ.get('MAXMIND_LICENSE_KEY') if account_id and license_key: print("\n--- Web Service Lookup ---") try: # Client objects are also expensive and should be reused. with geoip2.webservice.Client(account_id, license_key) as client: ip_address_ws = '1.1.1.1' try: response_ws = client.city(ip_address_ws) print(f"IP: {ip_address_ws}") print(f" Country: {response_ws.country.name} ({response_ws.country.iso_code})") print(f" City: {response_ws.city.name}") print(f" Location: Latitude {response_ws.location.latitude}, Longitude {response_ws.location.longitude}") except AddressNotFoundError: print(f"IP address {ip_address_ws} not found via web service.") except Exception as e: print(f"An error occurred during web service lookup for {ip_address_ws}: {e}") except Exception as e: print(f"Error initializing web service client: {e}") else: print("\nSkipping web service example: MAXMIND_ACCOUNT_ID and MAXMIND_LICENSE_KEY environment variables not set.")
Debug
Known issues
breakingVersion 5.0.0 and above require Python 3.10 or greater. Earlier Python versions should use an older `geoip2` release (e.g., v4.x.x for Python 3.9).
fix
Upgrade Python to 3.10+ or pin `geoip2` to an earlier major version (e.g., `geoip2<5`) if using older Python.
affects: >=5.0.0
breakingThe `raw` attribute on model classes has been replaced by a `to_dict()` method. Also, `ip_address` properties on models now consistently return `ipaddress.IPv4Address` or `ipaddress.IPv6Address` objects.
fix
Update code to use `.to_dict()` for dictionary representation and expect `ipaddress` objects for `ip_address` attributes.
affects: >=4.5.0
deprecatedThe `metro_code` on `geoip2.record.Location` is deprecated, as the code values are no longer maintained by MaxMind.
fix
Avoid using `metro_code` or consider alternative geographic identifiers if possible.
affects: >=4.5.0
deprecatedSeveral boolean properties (e.g., `is_anonymous`, `is_anonymous_vpn`) on `geoip2.records.Traits` have been deprecated in favor of a new `anonymizer` object within the `Insights` model.
fix
If using the Insights web service, refactor to use the `anonymizer` object for VPN and proxy information.
affects: >=4.5.0
gotchaFailure to handle `geoip2.errors.AddressNotFoundError` when an IP address is not found in the database or by the web service can lead to unhandled exceptions.
fix
Always wrap IP lookup calls in a `try...except geoip2.errors.AddressNotFoundError:` block to gracefully handle unknown IP addresses.
affects: All
gotchaThe `geoip2.database.Reader` and `geoip2.webservice.Client` objects are expensive to create. Instantiating them repeatedly in a loop will severely impact performance.
fix
Create `Reader` or `Client` objects once and reuse them for multiple lookups. Use `with` statements to ensure proper resource management (e.g., database file closure).
affects: All
gotchaUsing values from `names` properties (e.g., `response.country.name`) as keys in databases or dictionaries is discouraged, as these names may change between MaxMind releases. Instead, use stable identifiers.
fix
Rely on stable identifiers like `geoname_id`, `iso_code`, or other unique codes (e.g., `response.country.iso_code`, `response.city.geoname_id`).
affects: All
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'geoip2' OR ImportError: No module named geoip2.database
The 'geoip2' package is not installed in the Python environment being used, or there is a local script named 'geoip2.py' that is shadowing the actual library.
fix
Install the package using `pip install geoip2`. If the issue persists, rename any local script named `geoip2.py` or `geoip2.pyc` to avoid a name collision.
FileNotFoundError: [Errno 2] No such file or directory: '/path/to/GeoLite2-City.mmdb'
The specified GeoIP2 database file (e.g., GeoLite2-City.mmdb) does not exist at the provided path, or the application lacks the necessary read permissions for the file or its directory.
fix
Ensure the database file exists at the exact path provided to `geoip2.database.Reader()`. Verify the file name and extension are correct. Download the latest GeoLite2 or GeoIP2 database from MaxMind and place it in the expected directory, then check file permissions.
maxminddb.errors.InvalidDatabaseError: The MaxMind DB file's search tree is corrupt OR Error opening database file (...). Is this a valid MaxMind DB file?
The provided .mmdb database file is corrupted, not a valid MaxMind DB format, or its format is incompatible with the installed 'geoip2' or 'maxminddb' library version.
fix
Redownload a fresh, uncorrupted copy of the GeoIP2 database from MaxMind. Ensure your 'geoip2' and 'maxminddb' Python packages are updated to their latest stable versions to guarantee compatibility with the database format.
geoip2.errors.AddressNotFoundError: The address X.X.X.X is not in the database.
The IP address queried is not present in the loaded GeoIP2 database. This commonly occurs for private, reserved, or certain unallocated IP addresses for which MaxMind does not provide public geolocation data.
fix
Implement error handling (a `try-except` block) for `geoip2.errors.AddressNotFoundError` to gracefully manage cases where an IP address lookup yields no results. Consider if the IP is intentionally not in the database (e.g., a local network IP).
AttributeError: 'City' object has no attribute 'name' (or similar for other attributes like country.iso_code returning None)
While the IP lookup was successful, the specific attribute requested (e.g., city name, country ISO code) does not have data available in the loaded GeoIP2 database for that particular IP address.
fix
Always check if the attribute's value is not `None` before attempting to access sub-attributes or perform operations on it. This indicates that MaxMind does not have that specific piece of information for the given IP address in the database version you are using.
Upgrade
Version history
5.2.0latest on PyPI
Audit
Dependencies
maxminddbrequiredRequired for reading local MaxMind DB files (often installed as a dependency of geoip2).
requestsoptionalUsed by the synchronous web service client.
aiohttpoptionalUsed by the asynchronous web service client.
Agent activity
13 hits · last 30 days
seranking-bot
4
ahrefsbot
3
node
2
googlebot
2
amazonbot
1
Resources