"""IPzentra Python client 1.0.0. MIT licence. Docs: https://ipzentra.com/docs Needs Python 3.8+. No dependencies. from ipzentra import Client ipz = Client("ipz_your_key") r = ipz.check("49.207.48.1", ["IN"]) if not r["country_match"] or r["is_vpn"]: ... """ import json import time import urllib.error import urllib.parse import urllib.request __version__ = "1.0.0" __all__ = ["Client", "IPzentraError"] class IPzentraError(Exception): """Raised for any non-2xx answer or network failure. status: HTTP status (0 for a network error) code: machine-readable code, for example rate_limited or invalid_key body: decoded error body, or None """ def __init__(self, status, code, message, body=None): super().__init__(message) self.status, self.code, self.body = status, code, body class Client: def __init__(self, api_key, base_url="https://api.ipzentra.com", timeout=10.0, retries=1): self.api_key = api_key self.base_url = base_url.rstrip("/") self.timeout = timeout self.retries = retries self.remaining_today = None # lookups left today, from the last response def lookup(self, ip): """Look up one IPv4 or IPv6 address.""" return self._request("GET", "/v1/" + urllib.parse.quote(ip, safe="")) def me(self): """Look up the IP address of the machine making the call.""" return self._request("GET", "/v1/") def check(self, ip, countries): """Look up an IP and compare it with the countries you expect. countries: ["IN", "SG"] or "IN,SG".""" return self._request("GET", "/v1/check?" + urllib.parse.urlencode({"ip": ip, "country": self._countries(countries)})) def batch(self, ips, countries=None): """Look up up to 100 IPs in one request. Returns {"count": n, "ok": n, "results": [...]}.""" body = {"ips": list(ips)} if countries: body["country"] = self._countries(countries) return self._request("POST", "/v1/batch", body) def health(self): """Service status. Does not use your quota.""" return self._request("GET", "/health") @staticmethod def _countries(c): return (",".join(c) if isinstance(c, (list, tuple, set)) else str(c)).replace(" ", "").upper() def _request(self, method, path, body=None): attempt = 0 while True: data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(self.base_url + path, data=data, method=method) req.add_header("X-Api-Key", self.api_key) req.add_header("Accept", "application/json") req.add_header("User-Agent", "ipzentra-python/" + __version__) if data is not None: req.add_header("Content-Type", "application/json") try: with urllib.request.urlopen(req, timeout=self.timeout) as resp: self._remaining(resp.headers) return json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: self._remaining(e.headers) if e.code >= 500 and attempt < self.retries: attempt += 1 time.sleep(0.3 * attempt) continue try: err = json.loads(e.read().decode("utf-8")) except Exception: err = None err = err if isinstance(err, dict) else None raise IPzentraError(e.code, (err or {}).get("error", "http_%d" % e.code), (err or {}).get("message", "IPzentra returned HTTP %d" % e.code), err) from None except (urllib.error.URLError, TimeoutError, OSError) as e: if attempt < self.retries: attempt += 1 time.sleep(0.3 * attempt) continue raise IPzentraError(0, "network_error", "Could not reach IPzentra: %s" % e) from None def _remaining(self, headers): v = headers.get("X-RateLimit-Remaining-Day") if headers else None if v is not None and str(v).lstrip("-").isdigit(): self.remaining_today = int(v)