On this page
  1. urllib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Building Safe Requests with Explicit Timeouts & Error Handling
  7. 2. Percent-Encoding Path Segments & Query Strings
  8. Gotchas & Boundaries

urllib

Prev: unittest | Up: stdlib_module | Next: uuid
Rel: email, json, mailbox, mimetypes, base64
Ref: docs.python.org — urllib
Tags: #public #python3 #stdlib


Import

from urllib import parse, request, error

Overview

Package grouping Python's standard-library URL and HTTP utilities across four submodules: urllib.parse (URL parsing, joining, quoting, and query encoding), urllib.request (HTTP/HTTPS client), urllib.error (HTTPError, URLError), and urllib.robotparser. Always import the specific submodule (from urllib.parse import ..., from urllib.request import ...) rather than bare import urllib.

Quick Start

from urllib.parse import parse_qs, urlencode, urljoin, urlsplit

base = "https://example.org/v1/"
endpoint = urljoin(base, "search") + "?" + urlencode({"q": "python stdlib", "page": 2})
parts = urlsplit(endpoint)

assert parts.scheme == "https"
assert parts.netloc == "example.org"
assert parse_qs(parts.query) == {"q": ["python stdlib"], "page": ["2"]}

Implementation Walkthrough

1. Building Safe Requests with Explicit Timeouts & Error Handling

When using urllib.request, construct a Request with explicit headers, set a timeout, and cap bytes read from the stream:

from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen

def read_limited(url: str, *, timeout: float = 10.0, max_bytes: int = 1_000_000) -> bytes:
    req = Request(url, headers={"Accept": "application/json"})
    try:
        with urlopen(req, timeout=timeout) as resp:
            data = resp.read(max_bytes + 1)
            if len(data) > max_bytes:
                raise ValueError("Response exceeded max_bytes")
            return data
    except HTTPError as exc:
        raise RuntimeError(f"HTTP {exc.code}: {exc.reason}") from exc
    except URLError as exc:
        raise ConnectionError(f"Request failed: {exc.reason}") from exc

2. Percent-Encoding Path Segments & Query Strings

from urllib.parse import quote, unquote

encoded = quote("notes/my file #1.md", safe="/")
assert encoded == "notes/my%20file%20%231.md"
assert unquote(encoded) == "notes/my file #1.md"

Gotchas & Boundaries

Linked from

Related notes