Skip to content

comicbox.readinglists.sources.url

Fetch a reading list from a URL, streamed and bounded.

A body is read raw and capped on the wire; a gzip or deflate body is inflated here, never past the cap, and any other encoding is refused. So a few kilobytes that would inflate to gigabytes cost no more memory than the cap. A whole download has a deadline, and a cancel is honoured between chunks.

Download dataclass

A fetched body, with the status and headers it came with.

Source code in comicbox/readinglists/sources/url.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@dataclass(frozen=True, slots=True)
class Download:
    """A fetched body, with the status and headers it came with."""

    status: int
    headers: Mapping[str, str]
    body: bytes

    @property
    def not_modified(self) -> bool:
        """Whether a conditional request found nothing new."""
        return self.status == HTTPStatus.NOT_MODIFIED

    @property
    def revision(self) -> str:
        """Name the version fetched: its ETag, its date, or when it was fetched."""
        return (
            self.headers.get(_ETAG)
            or self.headers.get(_LAST_MODIFIED)
            or datetime.now(tz=UTC).isoformat(timespec="seconds")
        )

not_modified property

Whether a conditional request found nothing new.

revision property

Name the version fetched: its ETag, its date, or when it was fetched.

HttpStatusError

Bases: ReadingListFetchError

A fetch the server answered with an error status.

Source code in comicbox/readinglists/sources/url.py
53
54
55
56
57
58
59
60
class HttpStatusError(ReadingListFetchError):
    """A fetch the server answered with an error status."""

    def __init__(self, url: str, response: httpx.Response) -> None:
        """Name the URL and the status; keep the status and headers."""
        self.status = response.status_code
        self.headers: Mapping[str, str] = response.headers
        super().__init__(f"{url}: HTTP {self.status} {response.reason_phrase}.")

__init__(url, response)

Name the URL and the status; keep the status and headers.

Source code in comicbox/readinglists/sources/url.py
56
57
58
59
60
def __init__(self, url: str, response: httpx.Response) -> None:
    """Name the URL and the status; keep the status and headers."""
    self.status = response.status_code
    self.headers: Mapping[str, str] = response.headers
    super().__init__(f"{url}: HTTP {self.status} {response.reason_phrase}.")

check_url(url)

Refuse anything but an http or https URL.

Source code in comicbox/readinglists/sources/url.py
109
110
111
112
113
114
def check_url(url: str) -> str:
    """Refuse anything but an http or https URL."""
    if urlsplit(url).scheme.lower() not in _SCHEMES:
        reason = f"Only http and https URLs can be fetched: {without_userinfo(url)}"
        raise ReadingListFetchError(reason)
    return url

download(client, url, max_bytes, headers=None, *, cancelled=None)

Download a URL’s body, sending headers with the request.

Redirects are followed, but only to http and https. A 304 comes back with an empty body. An error status raises HttpStatusError; a network failure, a body over max_bytes in either its sent or its inflated size, an encoding other than gzip or deflate, or a download past DEADLINE_SECONDS, ReadingListFetchError. cancelled is asked between chunks; when it says yes, OnlineLookupAbortedError.

Source code in comicbox/readinglists/sources/url.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def download(
    client: httpx.Client,
    url: str,
    max_bytes: int,
    headers: Mapping[str, str] | None = None,
    *,
    cancelled: Callable[[], bool] | None = None,
) -> Download:
    """
    Download a URL's body, sending ``headers`` with the request.

    Redirects are followed, but only to http and https. A 304 comes back
    with an empty body. An error status raises ``HttpStatusError``; a
    network failure, a body over ``max_bytes`` in either its sent or its
    inflated size, an encoding other than gzip or deflate, or a download
    past ``DEADLINE_SECONDS``, ``ReadingListFetchError``. ``cancelled`` is
    asked between chunks; when it says yes, ``OnlineLookupAbortedError``.
    """
    import httpx

    check_url(url)
    # What every message shows: the userinfo is for the request alone.
    shown = without_userinfo(url)
    request_headers = {**(headers or {}), "Accept-Encoding": _ACCEPT_ENCODING}
    try:
        with client.stream("GET", url, headers=request_headers) as response:
            check_url(str(response.url))
            if response.is_error:
                raise HttpStatusError(shown, response)
            body = (
                b""
                if response.status_code == HTTPStatus.NOT_MODIFIED
                else _BoundedBody(response, shown, max_bytes, cancelled).read()
            )
            return Download(response.status_code, response.headers, body)
    except (httpx.HTTPError, httpx.InvalidURL, httpx.StreamError) as exc:
        # InvalidURL is not an HTTPError: a URL with a newline, a bad host
        # name, or a redirect to one, such as "javascript:...".
        reason = f"Cannot fetch {shown}: {_scrub(str(exc), url)}"
        raise ReadingListFetchError(reason) from exc

fetch(client, url, max_bytes, *, cancelled=None)

Download a URL’s body and a revision for it, as download does.

Source code in comicbox/readinglists/sources/url.py
271
272
273
274
275
276
277
278
279
280
def fetch(
    client: httpx.Client,
    url: str,
    max_bytes: int,
    *,
    cancelled: Callable[[], bool] | None = None,
) -> tuple[bytes, str]:
    """Download a URL's body and a revision for it, as ``download`` does."""
    fetched = download(client, url, max_bytes, cancelled=cancelled)
    return fetched.body, fetched.revision

without_userinfo(url)

Drop a URL’s user name and password, keeping the rest of the address.

They are sent with the request and never recorded or shown. The query string stays: it is part of the address.

Source code in comicbox/readinglists/sources/url.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def without_userinfo(url: str) -> str:
    """
    Drop a URL's user name and password, keeping the rest of the address.

    They are sent with the request and never recorded or shown. The query
    string stays: it is part of the address.
    """
    try:
        parts = urlsplit(url)
    except ValueError:
        return _USERINFO_RE.sub(r"\1", url)
    if "@" not in parts.netloc:
        return url
    host = parts.netloc.rpartition("@")[2]
    return urlunsplit((parts.scheme, host, parts.path, parts.query, parts.fragment))