Datasets:
File size: 3,124 Bytes
6fb01b2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | 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}")
|