File size: 1,416 Bytes
ac3dba3 98ee81b ac3dba3 | 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 | """Conditional GET with ETag, so unchanged data costs (almost) nothing.
License: Apache-2.0.
"""
from __future__ import annotations
import json
import urllib.error
import urllib.request
from typing import Any
class ConditionalFetcher:
"""Remember the last ETag and body per URL; send If-None-Match next time."""
def __init__(self, headers: dict[str, str] | None = None, timeout: float = 20.0):
self.headers = {"Accept": "application/json", "User-Agent": "example-agent/0.1"}
self.headers.update(headers or {})
self.timeout = timeout
self._cache: dict[str, tuple[str, Any]] = {}
def get(self, url: str) -> tuple[Any, bool]:
"""Return (data, changed). `changed` is False when the server sent 304."""
headers = dict(self.headers)
cached = self._cache.get(url)
if cached:
headers["If-None-Match"] = cached[0]
req = urllib.request.Request(url, headers=headers)
try:
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
data = json.loads(resp.read().decode("utf-8"))
etag = resp.headers.get("ETag")
if etag:
self._cache[url] = (etag, data)
return data, True
except urllib.error.HTTPError as err:
if err.code == 304 and cached:
return cached[1], False
raise
|