Complete worked example
python
from urllib.request import build_opener, HTTPRedirectHandler, ProxyHandler
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, request, file, code, message, headers, new_url):
return None
import json
from urllib.request import Request
from urllib.error import HTTPError
def invalid_constant(value):
raise ValueError("non-finite JSON constant")
def cached_document(url, cached=None):
headers = {}
if isinstance(cached, dict) and cached.get("url") == url and isinstance(cached.get("etag"), str):
headers["If-None-Match"] = cached["etag"]
try:
with build_opener(ProxyHandler({}), NoRedirect()).open(Request(url, headers=headers), timeout=2) as response:
if response.headers.get_content_type() != "application/json":
raise ValueError("JSON media type required")
raw, etag = response.read(4097), response.headers.get("ETag")
except HTTPError as error:
status = error.code
error.close()
if status == 304 and "If-None-Match" in headers:
return dict(cached)
raise
if len(raw) > 4096:
raise ValueError("response exceeds budget")
data = json.loads(raw.decode("utf-8"), parse_constant=invalid_constant)
if not isinstance(data, dict):
raise ValueError("object required")
return {"url": url, "etag": etag, "data": data}- Reasoning
- Reuse a cached representation only when its URL and validator belong to the requested resource. Compare the stated values and failure boundary before changing the implementation.