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
def invalid_constant(value):
raise ValueError("non-finite JSON constant")
def json_document(url, max_bytes=1024):
if type(max_bytes) is not int or not 1 <= max_bytes <= 4096:
raise ValueError("byte budget required")
opener = build_opener(ProxyHandler({}), NoRedirect())
with opener.open(url, timeout=2) as response:
if response.headers.get_content_type() != "application/json":
raise ValueError("JSON media type required")
raw = response.read(max_bytes + 1)
if len(raw) > max_bytes:
raise ValueError("response exceeds budget")
result = json.loads(raw.decode("utf-8"), parse_constant=invalid_constant)
if not isinstance(result, dict):
raise ValueError("object required")
return result- Reasoning
- Read a controlled HTTP response with an explicit timeout, byte budget, media type and parse boundary. Compare the stated values and failure boundary before changing the implementation.