Skip to content

Instantly share code, notes, and snippets.

@LeonardAukea
Last active September 12, 2018 20:03
Show Gist options
  • Save LeonardAukea/3d5ef3b743da6639968b13f45c155fb6 to your computer and use it in GitHub Desktop.
Save LeonardAukea/3d5ef3b743da6639968b13f45c155fb6 to your computer and use it in GitHub Desktop.
geolocate w/ ip address #python
import requests
import json
def geolocate_ip(ip):
'''Get location data based on ip.
Note: Limited (Free) to a 1000 requests per day.
TODO(Leonard): Handler for being behind a vpn
Inputs:
ip: str
Returns:
loc: dict with keys
'''
try:
geo_keys = ('continent_code',
'country',
'region',
'latitude',
'longitude',
'timezone',
'postal')
r = requests.get(f'https://ipapi.co/{ip}/json/')
loc = {k: r.json()[k] for k in geo_keys}
return loc
except requests.exceptions.HTTPError as e:
return logger.error(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment