Download modules/geoip.py from deanpowers/blind-monkeys: direct link, hf CLI and curl.
- Browser
- Download file 1.37 kB
-
https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/geoip.py
- Command line
-
hf download hf://deanpowers/blind-monkeys/modules/geoip.py
-
curl -L -o geoip.py https://huggingface.co/deanpowers/blind-monkeys/resolve/main/modules/geoip.py
1.37 kB
| """IP geolocation via DB-IP. Uses private API key (paid plan).""" | |
| import os | |
| import requests | |
| DBIP_API_KEY = os.environ.get("DBIP_API_KEY", "").strip() | |
| def get_client_ip(request_obj): | |
| """Extract real client IP, accounting for Cloud Run's proxy.""" | |
| forwarded = request_obj.headers.get("X-Forwarded-For") | |
| if forwarded: | |
| return forwarded.split(",")[0].strip() | |
| return request_obj.remote_addr or "" | |
| def lookup_geo(ip): | |
| """Return {city, country} for an IP, or None on failure.""" | |
| if not ip: | |
| return None | |
| # Skip private/local IPs | |
| if ip.startswith(("127.", "10.", "192.168.", "169.254.", "::1", "0.0.0.0")): | |
| return None | |
| if not DBIP_API_KEY: | |
| print("DBIP_API_KEY not set - skipping geo lookup") | |
| return None | |
| try: | |
| url = "https://api.db-ip.com/v2/" + DBIP_API_KEY + "/" + ip | |
| r = requests.get(url, timeout=5) | |
| if r.status_code != 200: | |
| print("Geo lookup " + ip + " returned " + str(r.status_code)) | |
| return None | |
| d = r.json() | |
| return { | |
| "city": d.get("city", ""), | |
| "country": d.get("countryName", ""), | |
| "country_code": d.get("countryCode", ""), | |
| "state": d.get("stateProv", ""), | |
| } | |
| except Exception as e: | |
| print("Geo lookup failed for " + ip + ": " + str(e)) | |
| return None | |