MaxMind DB Python Reader
This is a Python module for reading MaxMind DB files, a binary file format that stores data indexed by IP address subnets (IPv4 or IPv6). The library includes both a pure Python reader and an optional C extension for performance. It is actively maintained, with version 3.1.1 released on March 5, 2026, and follows Semantic Versioning.
Warnings
- gotcha Calling the `close()` method on a `Reader` object while reads are in progress in other threads may cause exceptions. The library is thread-safe for concurrent reads but closing should be done when no reads are active.
- gotcha Attempting to look up an invalid IP address string or an IPv6 address in an IPv4-only database will raise a `ValueError`.
- gotcha When opening a database with `maxminddb.Mode.FD` (file descriptor mode), it is the caller's responsibility to ensure the file descriptor is closed properly. The library will not manage the file descriptor's lifecycle.
- gotcha The `maxminddb` library only reads MaxMind DB files. You must first download or create a `.mmdb` database file (e.g., GeoLite2 from MaxMind) to use the library effectively.
Install
-
pip install maxminddb
Imports
- open_database
from maxminddb import open_database
- Mode
from maxminddb import Mode
- InvalidDatabaseError
from maxminddb import InvalidDatabaseError
Quickstart
import maxminddb
import os
# You need a MaxMind DB file, e.g., GeoLite2-City.mmdb.
# Download free GeoLite2 databases from maxmind.com.
database_path = os.environ.get('MAXMIND_DB_PATH', 'GeoLite2-City.mmdb')
try:
with maxminddb.open_database(database_path) as reader:
# Look up an IPv4 address
ip_address_v4 = '152.216.7.110'
record_v4 = reader.get(ip_address_v4)
print(f'Record for {ip_address_v4}: {record_v4}')
# Look up an IPv6 address (if database supports it)
ip_address_v6 = '2001:4860:4860::8888'
record_v6 = reader.get(ip_address_v6)
print(f'Record for {ip_address_v6}: {record_v6}')
# Get metadata about the database
metadata = reader.metadata()
print(f'Database Type: {metadata.database_type}')
# Iterate over all networks and records (can be slow for large DBs)
# for network, record in reader:
# print(f'Network: {network}, Record: {record}')
except maxminddb.InvalidDatabaseError as e:
print(f'Error opening or reading database: {e}')
except ValueError as e:
print(f'Invalid IP address or incompatible database for IP version: {e}')
except FileNotFoundError:
print(f'Database file not found at: {database_path}')