maxmind-geoip2-python

repository·main·Indexed 22 days ago

https://github.com/maxmind/geoip2-python

A Python API for interacting with MaxMind's GeoIP and GeoLite web services and local MMDB databases for IP geolocation data. Version 5.3.0 provides synchronous and asynchronous clients for web services, as well as a Reader for local database lookups including City, Country, ASN, ISP, and Domain data.

Tokens
5.7K
Snippets
3
Records
39
Agent score
79%

What's inside geoip2

  1. Understand data availability and completeness

    main

    While many models share similar structures, the specific attributes populated vary depending on the database or web service endpoint used. MaxMind does not guarantee that every piece of data is available for every IP address.

    As a result, it is possible for a request to return a record where some or all attributes are unpopulated. The only piece of data guaranteed to be returned is the ip_address attribute within the geoip2.records.Traits record.

  2. How Web Service usage works

    main

    To use the MaxMind web services, you must instantiate either a geoip2.webservice.Client (synchronous) or a geoip2.webservice.AsyncClient (asynchronous).

    Configuration:

    • Pass your MaxMind account_id and license_key to the constructor.
    • Use the host keyword argument to switch environments:
      • Default: Production GeoIP web service.
      • host='geolite.info': GeoLite web service.
      • host='sandbox.maxmind.com': Sandbox GeoIP web service.

    Execution: Call the method corresponding to your request type (e.g., city, country, or insights) and pass the IP address. Note that insights is not supported by the GeoLite web service. Successful calls return a model class containing various record classes representing the returned data.

  3. Recommended keys for database or dictionary lookups

    main

    Do not use values from names properties (like city names or country names) as keys in your own databases or dictionaries, as these can change between releases.

    Instead, use the following stable identifiers:

    • City: city.geoname_id (from geoip2.records.City)
    • Continent: continent.code or continent.geoname_id (from geoip2.records.Continent)
    • Country: country.iso_code or country.geoname_id (from geoip2.records.Country or geoip2.records.RepresentedCountry)
    • Subdivision: subdivision.iso_code or subdivision.geoname_id (from geoip2.records.subdivision)
  4. How Database usage works

    main

    To use the local database API, construct a geoip2.database.Reader by passing the path to your MaxMind database file as the first argument.

    Once initialized, you can call methods corresponding to the database type (e.g., city or country) and pass the IP address you wish to look up. Successful lookups return a model class containing various record classes representing the data. If the lookup fails, the reader throws an exception.

  5. Install the geoip2 module

    main

    You can install the geoip2 package via PyPI using pip. If you are installing from a source directory, use python -m pip install ..

    Database Reader Extension: If you want to use the C extension for the database reader, you must first install the libmaxminddb C API following its own installation instructions.

    $ pip install geoip2
  6. Access network information from SimpleModel

    main

    Models that inherit from SimpleModel (such as AnonymousIP, ASN, ConnectionType, Domain, and ISP) provide access to the underlying IP address and its associated network.

    • ip_address: Returns the IPv4Address or IPv6Address associated with the record.
    • network: Returns an ipaddress.IPv4Network or ipaddress.IPv6Network object representing the largest network where all fields (besides the IP itself) remain the same. If the network cannot be determined, it returns None.
  7. Configure Locales for names

    main

    When initializing a client, you can provide a list of locales. This affects how the .name property of record classes (like city.name or country.name) behaves.

    • The client will return the name in the first locale in your list that has a valid entry for that record.
    • The locale en (English) is always present in the GeoIP data. If you do not include en in your locales list, the .name property might return None even if an English name exists.

    Supported Locales:

    • de (German)
    • en (English)
    • es (Spanish)
    • fr (French)
    • ja (Japanese)
    • pt-BR (Brazilian Portuguese)
    • ru (Russian)
    • zh-CN (Simplified Chinese)
  8. Understand the hierarchy of geolocation models

    main

    The geoip2 library uses a class hierarchy to represent different levels of geolocation data. Most models inherit from one another to provide increasing levels of detail:

    1. Country: The base model for country-level data. It includes continent, country, registered_country, represented_country, and traits.
    2. City: Inherits from Country and adds granular location data like city, location, postal, and subdivisions.
    3. Insights: Inherits from City and adds anonymizer data (VPN/proxy info).
    4. Enterprise: Inherits from City for GeoIP Enterprise database results.

    Depending on which MaxMind database or web service you use, you will receive one of these specific model types.

  9. Access localized names via PlaceRecord

    main
    Classes that inherit from PlaceRecord (such as City, Country, Continent, and Subdivision) support localized names. These records contain a names dictionary where keys are locale codes (e.g., 'en', 'fr') and values are the names in that locale. You can use the .name property to retrieve the name corresponding to the locales provided during initialization.
  10. Handle Database Reader exceptions

    main

    When working with local databases, be prepared to handle the following exceptions:

    • FileNotFoundError / PermissionError: Raised by the constructor if the database file is missing or unreadable.
    • ValueError: Raised if the provided IP address is invalid.
    • maxminddb.InvalidDatabaseError: Raised if the file is invalid or there is a reader bug.
    • geoip2.errors.AddressNotFoundError: Raised if the IP address is not present in the database. This exception includes a .network attribute which references the largest subnet where no address would be found, allowing for efficient subnet enumeration.
    import geoip2.database
    import geoip2.errors
    import ipaddress
    
    with geoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb') as reader:
        network = ipaddress.ip_network("192.128.0.0/15")
        ip_address = network[0]
        while ip_address in network:
            try:
                response = reader.asn(ip_address)
                response_network = response.network
            except geoip2.errors.AddressNotFoundError as e:
                response = None
                response_network = e.network
            print(f"{response_network}: {response!r}")
            ip_address = response_network[-1] + 1
  11. Use the synchronous Web Service Client

    main
    Use geoip2.webservice.Client for synchronous requests. It is recommended to use the client as a context manager to ensure resources are managed correctly. The client can be reused across multiple requests.
  12. Use the asynchronous Web Service Client

    main

    Use geoip2.webservice.AsyncClient for asynchronous requests within an event loop. The client should be used as an async context manager and can be reused across requests on the running event loop.

    Warning: If you are using multiple event loops, ensure the object is not used on another loop.