Fetch *url* and return raw bytes. Protections applied: - URL scheme validated (http / https only) - Redirects re-validated via _NoFileRedirectHandler - Response body capped at *max_bytes* (streaming read) - Non-2xx status raises urllib.error.HTTPError - Network errors propag
(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30)
| 271 | # --------------------------------------------------------------------------- |
| 272 | |
| 273 | def safe_fetch(url: str, max_bytes: int = _MAX_FETCH_BYTES, timeout: int = 30) -> bytes: |
| 274 | """Fetch *url* and return raw bytes. |
| 275 | |
| 276 | Protections applied: |
| 277 | - URL scheme validated (http / https only) |
| 278 | - Redirects re-validated via _NoFileRedirectHandler |
| 279 | - Response body capped at *max_bytes* (streaming read) |
| 280 | - Non-2xx status raises urllib.error.HTTPError |
| 281 | - Network errors propagate as urllib.error.URLError / OSError |
| 282 | |
| 283 | Raises: |
| 284 | ValueError - disallowed scheme or redirect target |
| 285 | urllib.error.HTTPError - non-2xx HTTP status |
| 286 | urllib.error.URLError - DNS / connection failure |
| 287 | OSError - size cap exceeded |
| 288 | """ |
| 289 | validate_url(url) |
| 290 | opener = _build_opener() |
| 291 | req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0 graphify/1.0"}) |
| 292 | |
| 293 | with opener.open(req, timeout=timeout) as resp: |
| 294 | # urllib raises HTTPError for non-2xx when using urlopen directly; |
| 295 | # with a custom opener we check manually to be safe. |
| 296 | status = getattr(resp, "status", None) or getattr(resp, "code", None) |
| 297 | if status is not None and not (200 <= status < 300): |
| 298 | raise urllib.error.HTTPError(url, status, f"HTTP {status}", {}, None) |
| 299 | |
| 300 | chunks: list[bytes] = [] |
| 301 | total = 0 |
| 302 | while True: |
| 303 | chunk = resp.read(65_536) |
| 304 | if not chunk: |
| 305 | break |
| 306 | total += len(chunk) |
| 307 | if total > max_bytes: |
| 308 | raise OSError( |
| 309 | f"Response from {url!r} exceeds size limit " |
| 310 | f"({max_bytes // 1_048_576} MB). Aborting download." |
| 311 | ) |
| 312 | chunks.append(chunk) |
| 313 | |
| 314 | return b"".join(chunks) |
| 315 | |
| 316 | |
| 317 | def safe_fetch_text(url: str, max_bytes: int = _MAX_TEXT_BYTES, timeout: int = 15) -> str: |