IP Geolocation in Python: Get Location from IP Address
Python is one of the most popular languages for backend development, data analysis, and scripting. Getting geolocation data from an IP address is a common task — whether you're building analytics dashboards, personalizing content, or logging visitor geography. This guide covers every approach.
The Simple Way: requests + Free API
The fastest way to get started — no API key, no library installation beyond requests:
import requests
response = requests.get("https://geo.kamero.ai/api/geo")
data = response.json()
print(f"IP: {data['ip']}")
print(f"City: {data['city']}")
print(f"Country: {data['country']}")
print(f"Timezone: {data['timezone']}")
print(f"Coordinates: {data['latitude']}, {data['longitude']}")This returns 10 fields: ip, city, country, countryRegion, continent, latitude, longitude, timezone, postalCode, and region.
With Error Handling
import requests
def get_geolocation():
try:
response = requests.get(
"https://geo.kamero.ai/api/geo",
timeout=5
)
response.raise_for_status()
return response.json()
except requests.RequestException as e:
print(f"Geolocation error: {e}")
return None
location = get_geolocation()
if location:
print(f"Welcome from {location.get('city', 'Unknown')}!")Flask Integration
Add visitor location to your Flask app:
from flask import Flask, request, jsonify
import requests as http_requests
app = Flask(__name__)
def get_visitor_location(ip_address):
"""Get location for a specific IP."""
try:
# For production, you'd forward the client IP
resp = http_requests.get(
"https://geo.kamero.ai/api/geo",
timeout=5
)
return resp.json()
except Exception:
return None
@app.route("/")
def home():
location = get_visitor_location(request.remote_addr)
city = location.get("city", "there") if location else "there"
return f"<h1>Hello from {city}!</h1>"
@app.route("/api/visitor-info")
def visitor_info():
location = get_visitor_location(request.remote_addr)
return jsonify(location or {"error": "Could not detect location"})Django Middleware
Automatically attach location data to every request in Django:
# middleware.py
import requests
class GeoLocationMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
try:
resp = requests.get(
"https://geo.kamero.ai/api/geo",
timeout=3
)
request.geo = resp.json()
except Exception:
request.geo = {}
return self.get_response(request)
# settings.py
MIDDLEWARE = [
"yourapp.middleware.GeoLocationMiddleware",
# ... other middleware
]
# views.py
def dashboard(request):
city = request.geo.get("city", "Unknown")
country = request.geo.get("country", "Unknown")
# Use location data in your viewCaching Results
For high-traffic apps, cache geolocation results to avoid redundant API calls:
from functools import lru_cache
import requests
@lru_cache(maxsize=1000)
def get_location_cached(ip: str) -> dict:
"""Cache location lookups by IP."""
try:
resp = requests.get(
"https://geo.kamero.ai/api/geo",
timeout=5
)
return resp.json()
except Exception:
return {}
# Or with Redis for distributed caching
import redis
import json
r = redis.Redis()
def get_location_redis(ip: str) -> dict:
cached = r.get(f"geo:{ip}")
if cached:
return json.loads(cached)
resp = requests.get("https://geo.kamero.ai/api/geo", timeout=5)
data = resp.json()
r.setex(f"geo:{ip}", 3600, json.dumps(data)) # Cache 1 hour
return dataData Analysis with pandas
If you're analyzing visitor data, combine geolocation with pandas:
import pandas as pd
import requests
# Assume you have a list of visitor IPs
visitor_ips = ["203.0.113.1", "198.51.100.2", "192.0.2.3"]
def lookup_ip(ip):
try:
resp = requests.get("https://geo.kamero.ai/api/geo", timeout=5)
return resp.json()
except Exception:
return {}
# Build a DataFrame
records = [lookup_ip(ip) for ip in visitor_ips]
df = pd.DataFrame(records)
# Analyze
print(df[["city", "country", "continent"]].value_counts())
print(f"\nUnique countries: {df['country'].nunique()}")
print(f"Most common city: {df['city'].mode()[0]}")Alternative: Self-Host for Full Control
For Python backends that need guaranteed uptime and zero external dependencies, you can deploy your own Kamero Geo API instance to Vercel and point your Python code at your own endpoint:
# Deploy your own instance, then:
GEO_API_URL = "https://geo.yourdomain.com/api/geo"
response = requests.get(GEO_API_URL, timeout=5)
location = response.json()