import threading import time import urllib.robotparser from urllib.parse import urlsplit import httpx USER_AGENT = "Dutch-GOV-Datasets (+https://github.com/ethux/Dutch-GOV-Datasets)" RETRY_STATUS = {429, 500, 502, 503, 504} class FetchError(Exception): pass class RateLimiter: """Spaces calls at least 1/per_second apart, across threads.""" def __init__(self, per_second: float): self.interval = 1.0 / per_second self.lock = threading.Lock() self.next_at = 0.0 def wait(self) -> None: with self.lock: now = time.monotonic() at = max(now, self.next_at) self.next_at = at + self.interval time.sleep(max(0.0, at - now)) class Fetcher: def __init__( self, per_second: float, *, max_retries: int = 5, backoff: float = 2.0, robots_exempt: set[str] = frozenset(), transport: httpx.BaseTransport | None = None, ): self.client = httpx.Client( headers={"User-Agent": USER_AGENT, "Accept": "application/xml, text/html;q=0.9, */*;q=0.8"}, timeout=120, follow_redirects=True, transport=transport, ) self.limiter = RateLimiter(per_second) self.max_retries = max_retries self.backoff = backoff self.robots_exempt = set(robots_exempt) self._robots: dict[str, urllib.robotparser.RobotFileParser] = {} self._robots_lock = threading.Lock() def allowed(self, url: str) -> bool: parts = urlsplit(url) if parts.hostname in self.robots_exempt: return True origin = f"{parts.scheme}://{parts.netloc}" with self._robots_lock: rp = self._robots.get(origin) if rp is None: rp = urllib.robotparser.RobotFileParser() try: r = self.client.get(origin + "/robots.txt") rp.parse(r.text.splitlines() if r.status_code == 200 else []) except httpx.HTTPError: rp.parse([]) self._robots[origin] = rp return rp.can_fetch(USER_AGENT, url) def get(self, url: str) -> httpx.Response: if not self.allowed(url): raise FetchError(f"disallowed by robots.txt: {url}") last = "" for attempt in range(self.max_retries + 1): self.limiter.wait() try: r = self.client.get(url) except httpx.TransportError as e: last = repr(e) except httpx.HTTPError as e: raise FetchError(f"{e!r}: {url}") from e else: if r.status_code == 200: return r if r.status_code not in RETRY_STATUS: raise FetchError(f"HTTP {r.status_code}: {url}") last = f"HTTP {r.status_code}" if attempt < self.max_retries: time.sleep(self.backoff**attempt if self.backoff else 0) raise FetchError(f"gave up after {self.max_retries} retries ({last}): {url}")