Looking to implement better geo-location with Python.
Maxmind has an official api package that integrates with their geoip web service or geolite databases. You'll have to either download their free geolite database or create a free trial account.
If you register for an account you'll get $5 in promotional credit (paid queries cost about $0.0001 each). Login to your account, click on 'My License Key' and create a license key.
Then install the package:
$ pip install geoip2
And test the api:
Test function adapted from the docs
import geoip2.webservice
account_id = 1 # enter your real account id here
api_key = "enter your real api/license key here"
TEST_IP = '128.101.101.101'
def lookup_ip(ip=TEST_IP):
# This creates a Client object that can be reused across requests.
client = geoip2.webservice.Client(account_id, api_key)
# Replace "insights" with the method corresponding to the web service
# that you are using, e.g., "country", "city".
response = client.insights(ip)
print("country iso code: {0}".format(response.country.iso_code))
print("country name: {0}".format(response.country.name))
print("subdivisions most specific name: {0}".format(response.subdivisions.most_specific.name))
print("subdivisions most specific iso code: {0}".format(response.subdivisions.most_specific.iso_code))
print("city name: {0}".format(response.city.name))
print("postal code:{0}".format(response.postal.code))
print("coordinates: ({0}, {1})".format(response.location.latitude, response.location.longitude))
return response
if __name__ == "__main__":
resp = lookup_ip()
input("")
It is not a Python lib. But http://ipinfodb.com/ provides a webservice that can be easily wrapped by Python code with urllib for example.
http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>&ip=74.125.45.100
http://api.ipinfodb.com/v3/ip-country/?key=<your_api_key>&ip=74.125.45.100
You need to request a free API key. See the API doc for details.
You may find these modules useful: MaxMind's GeoIP and its pure version, as well pytz.
IP API is also very nice way to do it.
import urllib
ip= '12.24.36.48'
url = 'http://ip-api.com/json/' + ip
req = urllib.request.Request(url)
out = urllib.request.urlopen(req).read()
I think freegeip is a good option. Below is the Python 3.4.2 code for getting location and time zone.
>>> import requests
>>> ip = '141.70.111.66'
>>> url = 'http://freegeoip.net/json/'+ip
>>> r = requests.get(url)
>>> js = r.json()
>>> js['country_code']
'DE'
>>> js['country_name']
'Germany'
>>> js['time_zone']
'Europe/Berlin'
You could use requests to make a call to my service https://ipdata.co
import requests
ip = '1.1.1.1'
response = requests.get('https://api.ipdata.co/{}'.format(ip)).json()
response['time_zone']