- Notifications
You must be signed in to change notification settings - Fork1
Python code for GeoIP2 webservice client and database reader
License
sg3-141-592/GeoIP2-python
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This package provides an API for the GeoIP2web services anddatabases. The API also works withMaxMind's freeGeoLite2 databases.
To install thegeoip2 module, type:
$ pip install geoip2$ pip install geoip2[aiohttp]$ pip install geoip2[requests]$ pip install geoip2[all]# Install both requests and aiohttp supportIf you are not able to use pip, you may also use easy_install from thesource directory:
$ easy_install.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 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.
To use this API, you first create either a web service object with yourMaxMindaccount_id andlicense_key or a database reader object with thepath to your database file. After doing this, you may call the methodcorresponding to request type (e.g.,city orcountry), passing it theIP address you want to look up.
If the request succeeds, the method call will return a model class for theend point 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.
>>>import geoip2.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.>>>with geoip2.webservice.Client(42,'license_key')as client:>>>>>># Replace "insights" with the method corresponding to the web service>>># that you are using, e.g., "country", "city".>>> response= client.insights('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')
>>>import asyncio>>>>>>import geoip2.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.>>>asyncwith geoip2.webservice.AsyncClient(42,'license_key')as client:>>>>>># Replace "insights" with the method corresponding to the web service>>># that you are using, e.g., "country", "city".>>> response=await client.insights('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())
For details on the possible errors returned by the web service itself, seehttp://dev.maxmind.com/geoip/geoip2/web-services for the GeoIP2 Precision 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.
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoLite2-City.mmdb')as reader:>>>>>># 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')
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoIP2-Anonymous-IP.mmdb')as reader:>>>>>> 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')
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoLite2-ASN.mmdb')as reader:>>> 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')
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoIP2-Connection-Type.mmdb')as reader:>>> 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')
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoIP2-Domain.mmdb')as reader:>>> response= reader.domain('203.0.113.0')>>> response.domain'umn.edu'>>> response.ip_address'203.0.113.0'
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoIP2-Enterprise.mmdb')as reader:>>>>>># 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')
>>>import geoip2.database>>>>>># This creates a Reader object. You should use the same object>>># across multiple requests as creation of it is expensive.>>>with geoip2.database.Reader('/path/to/GeoIP2-ISP.mmdb')as reader:>>> 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')
If the database file does not exist or is not readable, the constructor willraise aFileNotFoundError. If the IP address passed to a method isinvalid, aValueError will be raised. If the file is invalid or there is abug in the reader, amaxminddb.InvalidDatabaseError will be raised with adescription of the problem. If an IP address is not in the database, aAddressNotFoundError will be raised.
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_idgeoip2.records.Continent-continent.codeorcontinent.geoname_idgeoip2.records.Countryandgeoip2.records.RepresentedCountry-country.iso_codeorcountry.geoname_idgeoip2.records.subdivision-subdivision.iso_codeorsubdivision.geoname_id
While many of the models contain the same basic records, the attributes whichcan be populated vary between web service end points 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.
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.
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.
Python 3.6 or greater is required. Older versions are not supported.
The Requests HTTP library is also required. See<http://python-requests.org> for details.
The GeoIP2 Python API usesSemantic Versioning.
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.
About
Python code for GeoIP2 webservice client and database reader
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- Python98.9%
- Shell1.1%