markedet's picture
Add license files and NOTICE, update license fields
98ee81b verified
Raw History Blame Contribute Delete
1.42 kB
"""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