Download examples/conditional.py from markedet/agent-integration-guides: direct link, hf CLI and curl.
- Browser
- Download file 1.42 kB
-
https://huggingface.co/datasets/markedet/agent-integration-guides/resolve/main/examples/conditional.py
- Command line
-
hf download hf://datasets/markedet/agent-integration-guides/examples/conditional.py
-
curl -L -o conditional.py https://huggingface.co/datasets/markedet/agent-integration-guides/resolve/main/examples/conditional.py
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 | |