Typing Stubs for maxminddb

1.5.0 · active · verified Sun Apr 12

This package provides type hints for the `maxminddb` Python library, which is used for reading MaxMind DB files. These files store data indexed by IP address subnets (IPv4 or IPv6). `types-maxminddb` ensures that static type checkers like MyPy can validate usage of `maxminddb`. It is part of the `typeshed` project and its release cadence is tied to `typeshed` updates and `maxminddb`'s own releases. The current version is 1.5.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic usage of the `maxminddb` library, which `types-maxminddb` provides type hints for. To run this, you will need to have a MaxMind DB file (e.g., GeoLite2-City.mmdb) available. You can download free GeoLite2 databases from the MaxMind website. The code opens the database, performs an IP lookup, and iterates over a few entries. Ensure `MAXMIND_DB_PATH` is set or the database file is in the current directory.

import maxminddb
import os
from typing import Optional, Dict, Any

# You need a MaxMind DB file, e.g., GeoLite2-City.mmdb.
# Download a free GeoLite2 database from MaxMind: https://dev.maxmind.com/geoip/downloads/
# For local testing, place it in the current directory or set the environment variable.
DB_PATH = os.environ.get('MAXMIND_DB_PATH', 'GeoLite2-City.mmdb')

if not os.path.exists(DB_PATH):
    print(f"Warning: MaxMind DB file not found at {DB_PATH}.\n"
          "Please download one (e.g., GeoLite2-City.mmdb) and set MAXMIND_DB_PATH environment variable or place it in the current directory.")
    # Create a dummy file for the quickstart to be runnable, but advise user
    # that it won't actually work without a real DB.
    with open(DB_PATH, 'w') as f:
        f.write('dummy_db_content')
    dummy_db_used = True
else:
    dummy_db_used = False

try:
    # `reader` is inferred to be of type `maxminddb.Reader` due to type stubs
    with maxminddb.open_database(DB_PATH) as reader:
        ip_address = '8.8.8.8'
        record: Optional[Dict[str, Any]] = reader.get(ip_address)

        if record:
            print(f"Lookup for {ip_address}: {record}")
            # Example of accessing typed data if schema is known, e.g., GeoLite2-City
            country_name: Optional[str] = record.get('country', {}).get('names', {}).get('en')
            print(f"  Country (EN): {country_name}")
        else:
            print(f"No record found for {ip_address}")

        # Iterate over the database (useful for inspection)
        print("\nFirst 3 networks and records:")
        count = 0
        for network, record in reader: # `network` is IPv4Network or IPv6Network, `record` is Dict
            if count >= 3:
                break
            print(f"  Network: {network}, Record: {record}")
            count += 1

except maxminddb.InvalidDatabaseError as e:
    print(f"Error opening MaxMind DB: {e}. Ensure {DB_PATH} is a valid MaxMind DB file.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

if dummy_db_used:
    print(f"\nNote: A dummy DB file was created and used. For actual results, replace '{DB_PATH}' with a real MaxMind DB file.")
    os.remove(DB_PATH) # Clean up dummy file

view raw JSON →