Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
PyPI

geoip2 5.1.0

pip install geoip2

Latest version

Released:

MaxMind GeoIP2 API

Verified details

These details have beenverified by PyPI
Project links
Owner
GitHub Statistics

Unverified details

These details havenot been verified by PyPI
Project links
Meta

Project description

Description

This package provides an API for the GeoIP2 and GeoLite2web services anddatabases.

Installation

To install thegeoip2 module, type:

$pipinstallgeoip2

If you are not able to install from PyPI, you may also usepip from thesource directory:

$python-mpipinstall.

Database Reader Extension

If you wish to use the C extension for the database reader, you must firstinstall thelibmaxminddb C API.Pleasesee the instructions distributed with it.

IP Geolocation Usage

IP geolocation is inherently imprecise. Locations are often near the center ofthe population. Any location provided by a GeoIP2 database or web serviceshould not be used to identify a particular address or household.

Web Service Usage

To use this API, you first construct either ageoip2.webservice.Client orgeoip2.webservice.AsyncClient, passing your MaxMindaccount_id andlicense_key to the constructor. To use the GeoLite2 web service instead ofthe GeoIP2 web service, set the optionalhost keyword argument togeolite.info. To use the Sandbox GeoIP2 web service instead of theproduction GeoIP2 web service, set the optionalhost keyword argument tosandbox.maxmind.com.

After doing this, you may call the method corresponding to request type(e.g.,city orcountry), passing it the IP address you want to look up.

If the request succeeds, the method call will return a model class for theendpoint you called. This model in turn contains multiple record classes,each of which represents part of the data returned by the web service.

If the request fails, the client class throws an exception.

Sync Web Service Example

>>>importgeoip2.webservice>>>>>># This creates a Client object that can be reused across requests.>>># Replace "42" with your account ID and "license_key" with your license>>># key. Set the "host" keyword argument to "geolite.info" to use the>>># GeoLite2 web service instead of the GeoIP2 web service. Set the>>># "host" keyword argument to "sandbox.maxmind.com" to use the Sandbox>>># GeoIP2 web service instead of the production GeoIP2 web service.>>>withgeoip2.webservice.Client(42,'license_key')asclient:>>>>>># Replace "city" with the method corresponding to the web service>>># that you are using, i.e., "country", "city", or "insights". Please>>># note that Insights is not supported by the GeoLite2 web service.>>>response=client.city('203.0.113.0')>>>>>>response.country.iso_code'US'>>>response.country.name'United States'>>>response.country.names['zh-CN']u'美国'>>>>>>response.subdivisions.most_specific.name'Minnesota'>>>response.subdivisions.most_specific.iso_code'MN'>>>>>>response.city.name'Minneapolis'>>>>>>response.postal.code'55455'>>>>>>response.location.latitude44.9733>>>response.location.longitude-93.2323>>>>>>response.traits.networkIPv4Network('203.0.113.0/32')

Async Web Service Example

>>>importasyncio>>>>>>importgeoip2.webservice>>>>>>asyncdefmain():>>># This creates an AsyncClient object that can be reused across>>># requests on the running event loop. If you are using multiple event>>># loops, you must ensure the object is not used on another loop.>>>#>>># Replace "42" with your account ID and "license_key" with your license>>># key. Set the "host" keyword argument to "geolite.info" to use the>>># GeoLite2 web service instead of the GeoIP2 web service. Set the>>># "host" keyword argument to "sandbox.maxmind.com" to use the Sandbox>>># GeoIP2 web service instead of the production GeoIP2 web service.>>>asyncwithgeoip2.webservice.AsyncClient(42,'license_key')asclient:>>>>>># Replace "city" with the method corresponding to the web service>>># that you are using, i.e., "country", "city", or "insights". Please>>># note that Insights is not supported by the GeoLite2 web service.>>>response=awaitclient.city('203.0.113.0')>>>>>>response.country.iso_code'US'>>>response.country.name'United States'>>>response.country.names['zh-CN']u'美国'>>>>>>response.subdivisions.most_specific.name'Minnesota'>>>response.subdivisions.most_specific.iso_code'MN'>>>>>>response.city.name'Minneapolis'>>>>>>response.postal.code'55455'>>>>>>response.location.latitude44.9733>>>response.location.longitude-93.2323>>>>>>response.traits.networkIPv4Network('203.0.113.0/32')>>>>>>asyncio.run(main())

Web Service Client Exceptions

For details on the possible errors returned by the web service itself, seehttps://dev.maxmind.com/geoip/docs/web-services?lang=en for the GeoIP2 webservice docs.

If the web service returns an explicit error document, this is thrown as aAddressNotFoundError,AuthenticationError,InvalidRequestError, orOutOfQueriesError as appropriate. These all subclassGeoIP2Error.

If some other sort of error occurs, this is thrown as anHTTPError. Thisis thrown when some sort of unanticipated error occurs, such as the webservice returning a 500 or an invalid error document. If the web servicereturns any status code besides 200, 4xx, or 5xx, this also becomes anHTTPError.

Finally, if the web service returns a 200 but the body is invalid, the clientthrows aGeoIP2Error.

Database Usage

To use the database API, you first construct ageoip2.database.Reader usingthe path to the file as the first argument. After doing this, you may call themethod corresponding to database type (e.g.,city orcountry), passing itthe IP address you want to look up.

If the lookup succeeds, the method call will return a model class for thedatabase method you called. This model in turn contains multiple record classes,each of which represents part of the data for the record.

If the request fails, the reader class throws an exception.

Database Example

City Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoLite2-City.mmdb')asreader:>>>>>># Replace "city" with the method corresponding to the database>>># that you are using, e.g., "country".>>>response=reader.city('203.0.113.0')>>>>>>response.country.iso_code'US'>>>response.country.name'United States'>>>response.country.names['zh-CN']u'美国'>>>>>>response.subdivisions.most_specific.name'Minnesota'>>>response.subdivisions.most_specific.iso_code'MN'>>>>>>response.city.name'Minneapolis'>>>>>>response.postal.code'55455'>>>>>>response.location.latitude44.9733>>>response.location.longitude-93.2323>>>>>>response.traits.networkIPv4Network('203.0.113.0/24')

Anonymous IP Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoIP2-Anonymous-IP.mmdb')asreader:>>>>>>response=reader.anonymous_ip('203.0.113.0')>>>>>>response.is_anonymousTrue>>>response.is_anonymous_vpnFalse>>>response.is_hosting_providerFalse>>>response.is_public_proxyFalse>>>response.is_residential_proxyFalse>>>response.is_tor_exit_nodeTrue>>>response.ip_address'203.0.113.0'>>>response.networkIPv4Network('203.0.113.0/24')

Anonymous Plus Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoIP-Anonymous-Plus.mmdb')asreader:>>>>>>response=reader.anonymous_plus('203.0.113.0')>>>>>>response.anonymizer_confidence30>>>response.is_anonymousTrue>>>response.is_anonymous_vpnTrue>>>response.is_hosting_providerFalse>>>response.is_public_proxyFalse>>>response.is_residential_proxyFalse>>>response.is_tor_exit_nodeFalse>>>response.ip_address'203.0.113.0'>>>response.networkIPv4Network('203.0.113.0/24')>>>response.network_last_seendatetime.date(2025, 4, 18)>>>response.provider_nameFooBar VPNs

ASN Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb')asreader:>>>response=reader.asn('203.0.113.0')>>>response.autonomous_system_number1221>>>response.autonomous_system_organization'Telstra Pty Ltd'>>>response.ip_address'203.0.113.0'>>>response.networkIPv4Network('203.0.113.0/24')

Connection-Type Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoIP2-Connection-Type.mmdb')asreader:>>>response=reader.connection_type('203.0.113.0')>>>response.connection_type'Corporate'>>>response.ip_address'203.0.113.0'>>>response.networkIPv4Network('203.0.113.0/24')

Domain Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoIP2-Domain.mmdb')asreader:>>>response=reader.domain('203.0.113.0')>>>response.domain'umn.edu'>>>response.ip_address'203.0.113.0'

Enterprise Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoIP2-Enterprise.mmdb')asreader:>>>>>># Use the .enterprise method to do a lookup in the Enterprise database>>>response=reader.enterprise('203.0.113.0')>>>>>>response.country.confidence99>>>response.country.iso_code'US'>>>response.country.name'United States'>>>response.country.names['zh-CN']u'美国'>>>>>>response.subdivisions.most_specific.name'Minnesota'>>>response.subdivisions.most_specific.iso_code'MN'>>>response.subdivisions.most_specific.confidence77>>>>>>response.city.name'Minneapolis'>>>response.country.confidence11>>>>>>response.postal.code'55455'>>>>>>response.location.accuracy_radius50>>>response.location.latitude44.9733>>>response.location.longitude-93.2323>>>>>>response.traits.networkIPv4Network('203.0.113.0/24')

ISP Database

>>>importgeoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>withgeoip2.database.Reader('/path/to/GeoIP2-ISP.mmdb')asreader:>>>response=reader.isp('203.0.113.0')>>>response.autonomous_system_number1221>>>response.autonomous_system_organization'Telstra Pty Ltd'>>>response.isp'Telstra Internet'>>>response.organization'Telstra Internet'>>>response.ip_address'203.0.113.0'>>>response.networkIPv4Network('203.0.113.0/24')

Database Reader Exceptions

If the database file does not exist or is not readable, the constructor willraise aFileNotFoundError or aPermissionError. If the IP address passedto a method is invalid, aValueError will be raised. If the file is invalidor there is a bug in the reader, amaxminddb.InvalidDatabaseError will beraised with a description of the problem. If an IP address is not in thedatabase, aAddressNotFoundError will be raised.

AddressNotFoundError references the largest subnet where no address would befound. This can be used to efficiently enumerate entire subnets:

importgeoip2.databaseimportgeoip2.errorsimportipaddress# This creates a Reader object. You should use the same object# across multiple requests as creation of it is expensive.withgeoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb')asreader:network=ipaddress.ip_network("192.128.0.0/15")ip_address=network[0]whileip_addressinnetwork:try:response=reader.asn(ip_address)response_network=response.networkexceptgeoip2.errors.AddressNotFoundErrorase:response=Noneresponse_network=e.networkprint(f"{response_network}:{response!r}")ip_address=response_network[-1]+1# move to next subnet

Values to use for Database or Dictionary Keys

We strongly discourage you from using a value from any ``names`` property asa key in a database or dictionaries.

These names may change between releases. Instead we recommend using one of thefollowing:

  • geoip2.records.City -city.geoname_id

  • geoip2.records.Continent -continent.code orcontinent.geoname_id

  • geoip2.records.Country andgeoip2.records.RepresentedCountry -country.iso_code orcountry.geoname_id

  • geoip2.records.subdivision -subdivision.iso_code orsubdivision.geoname_id

What data is returned?

While many of the models contain the same basic records, the attributes whichcan be populated vary between web service endpoints or databases. Inaddition, while a model may offer a particular piece of data, MaxMind does notalways have every piece of data for any given IP address.

Because of these factors, it is possible for any request to return a recordwhere some or all of the attributes are unpopulated.

The only piece of data which is always returned is theip_addressattribute in thegeoip2.records.Traits record.

Integration with GeoNames

GeoNames offers web services and downloadabledatabases with data on geographical features around the world, includingpopulated places. They offer both free and paid premium data. Each feature isuniquely identified by ageoname_id, which is an integer.

Many of the records returned by the GeoIP web services and databases include ageoname_id field. This is the ID of a geographical feature (city, region,country, etc.) in the GeoNames database.

Some of the data that MaxMind provides is also sourced from GeoNames. Wesource things like place names, ISO codes, and other similar data from theGeoNames premium data set.

Reporting Data Problems

If the problem you find is that an IP address is incorrectly mapped, pleasesubmit your correction to MaxMind.

If you find some other sort of mistake, like an incorrect spelling, pleasecheck theGeoNames site first. Once you’vesearched for a place and found it on the GeoNames map view, there are anumber of links you can use to correct data (“move”, “edit”, “alternatenames”, etc.). Once the correction is part of the GeoNames data set, itwill be automatically incorporated into future MaxMind releases.

If you are a paying MaxMind customer and you’re not sure where to submit acorrection, pleasecontact MaxMind support for help.

Requirements

Python 3.9 or greater is required. Older versions are not supported.

The Requests HTTP library is also required. See<https://pypi.org/project/requests/> for details.

Versioning

The GeoIP2 Python API usesSemantic Versioning.

Support

Please report all issues with this code using theGitHub issue tracker

If you are having an issue with a MaxMind service that is not specific to theclient API, please contactMaxMind support for assistance.

Project details

Verified details

These details have beenverified by PyPI
Project links
Owner
GitHub Statistics

Unverified details

These details havenot been verified by PyPI
Project links
Meta

Release historyRelease notifications |RSS feed

This version

5.1.0

Download files

Download the file for your platform. If you're not sure which to choose, learn more aboutinstalling packages.

Source Distribution

geoip2-5.1.0.tar.gz (268.2 kBview details)

UploadedSource

Built Distribution

Filter files by name, interpreter, ABI, and platform.

If you're not sure about the file name format, learn more aboutwheel file names.

Copy a direct link to the current filters

geoip2-5.1.0-py3-none-any.whl (27.7 kBview details)

UploadedPython 3

File details

Details for the filegeoip2-5.1.0.tar.gz.

File metadata

  • Download URL:geoip2-5.1.0.tar.gz
  • Upload date:
  • Size: 268.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for geoip2-5.1.0.tar.gz
AlgorithmHash digest
SHA256ee3f87f0ce9325eb6484fe18cbd9771a03d0a2bad1dd156fa3584fafa562d39a
MD51c7b5808429cfc39f44c732101ebddc2
BLAKE2b-2560f5f902835f485d1c423aca9097a0e91925d6a706049f64e678ec781b168734d

See more details on using hashes here.

Provenance

The following attestation bundles were made forgeoip2-5.1.0.tar.gz:

Publisher:release.yml on maxmind/GeoIP2-python

Attestations:Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the filegeoip2-5.1.0-py3-none-any.whl.

File metadata

  • Download URL:geoip2-5.1.0-py3-none-any.whl
  • Upload date:
  • Size: 27.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for geoip2-5.1.0-py3-none-any.whl
AlgorithmHash digest
SHA256445a058995ad5bb3e665ae716413298d4383b1fb38d372ad59b9b405f6b0ca19
MD51c9a4f07df99d9063a3b76709dabbd23
BLAKE2b-256eb43aa9a10d0c971d0a0e353111a97913357f9271fb9a9867ec1053f79ca61be

See more details on using hashes here.

Provenance

The following attestation bundles were made forgeoip2-5.1.0-py3-none-any.whl:

Publisher:release.yml on maxmind/GeoIP2-python

Attestations:Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security SponsorDatadog MonitoringDepot Continuous IntegrationFastly CDNGoogle Download AnalyticsPingdom MonitoringSentry Error loggingStatusPage Status page

[8]ページ先頭

©2009-2025 Movatter.jp