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.parse import urlencode
def invalid_constant(value):
raise ValueError("non-finite JSON constant")
def client_report(base_url, country, max_pages=3):
if not isinstance(country, str) or country not in {"US", "IL", "UA", "CA"}:
raise ValueError("supported country required")
if type(max_pages) is not int or not 1 <= max_pages <= 5:
raise ValueError("bounded page count required")
opener = build_opener(ProxyHandler({}), NoRedirect())
cursor, visited, records = None, set(), {}
for _ in range(max_pages):
if cursor in visited:
raise ValueError("cursor cycle")
visited.add(cursor)
query = {"country": country}
if cursor is not None:
query["cursor"] = cursor
with opener.open(base_url + "/jobs?" + urlencode(query), timeout=2) as response:
if response.headers.get_content_type() != "application/json":
raise ValueError("JSON media type required")
raw = response.read(4097)
if len(raw) > 4096:
raise ValueError("response exceeds budget")
page = json.loads(raw.decode("utf-8"), parse_constant=invalid_constant)
if not isinstance(page, dict) or "next" not in page or not isinstance(page.get("items"), list):
raise ValueError("page shape required")
for row in page["items"]:
if not isinstance(row, dict) or type(row.get("active")) is not bool:
raise ValueError("role object and boolean state required")
if any(not isinstance(row.get(key), str) or not 1 <= len(row[key].strip()) <= 80 for key in ("id", "company", "country")):
raise ValueError("bounded text fields required")
normalized = {key: row[key].strip() for key in ("id", "company", "country")}
normalized["country"] = normalized["country"].upper()
if len(normalized["country"]) != 2 or not normalized["country"].isascii() or not normalized["country"].isalpha():
raise ValueError("country code required")
normalized["active"] = row["active"]
previous = records.get(normalized["id"])
if previous is not None and previous != normalized:
raise ValueError("conflicting identity")
records[normalized["id"]] = normalized
cursor = page["next"]
if cursor is None:
break
if not isinstance(cursor, str) or not cursor:
raise ValueError("invalid next cursor")
else:
raise ValueError("incomplete collection")
selected = [row for row in records.values() if row["active"] and row["country"] == country]
return {"ids": sorted(row["id"] for row in selected), "companies": len({row["company"] for row in selected})}- Reasoning
- Compose controlled HTTP, explicit pagination and source identity into one country-scoped report that refuses incomplete evidence. Compare the stated values and failure boundary before changing the implementation.