action0-req 0.3.0__tar.gz → 0.3.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {action0_req-0.3.0 → action0_req-0.3.1}/CHANGELOG.md +29 -0
  2. {action0_req-0.3.0 → action0_req-0.3.1}/CLAUDE.md +1 -0
  3. {action0_req-0.3.0 → action0_req-0.3.1}/PKG-INFO +17 -2
  4. {action0_req-0.3.0 → action0_req-0.3.1}/README.md +15 -0
  5. {action0_req-0.3.0 → action0_req-0.3.1}/docs/api.md +7 -0
  6. {action0_req-0.3.0 → action0_req-0.3.1}/docs/usage.md +72 -0
  7. {action0_req-0.3.0 → action0_req-0.3.1}/pyproject.toml +5 -4
  8. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/__init__.py +5 -1
  9. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/headers.py +32 -2
  10. action0_req-0.3.1/src/action0/req/multipart.py +431 -0
  11. {action0_req-0.3.0 → action0_req-0.3.1}/tests/action0/req/test_headers.py +155 -0
  12. action0_req-0.3.1/tests/action0/req/test_multipart.py +434 -0
  13. {action0_req-0.3.0 → action0_req-0.3.1}/uv.lock +4 -4
  14. {action0_req-0.3.0 → action0_req-0.3.1}/.github/workflows/ci.yml +0 -0
  15. {action0_req-0.3.0 → action0_req-0.3.1}/.github/workflows/release.yml +0 -0
  16. {action0_req-0.3.0 → action0_req-0.3.1}/.gitignore +0 -0
  17. {action0_req-0.3.0 → action0_req-0.3.1}/.python-version +0 -0
  18. {action0_req-0.3.0 → action0_req-0.3.1}/LICENSE +0 -0
  19. {action0_req-0.3.0 → action0_req-0.3.1}/docs/changelog.md +0 -0
  20. {action0_req-0.3.0 → action0_req-0.3.1}/docs/conf.py +0 -0
  21. {action0_req-0.3.0 → action0_req-0.3.1}/docs/index.md +0 -0
  22. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/body.py +0 -0
  23. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/py.typed +0 -0
  24. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/request.py +0 -0
  25. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/response.py +0 -0
  26. {action0_req-0.3.0 → action0_req-0.3.1}/src/action0/req/status.py +0 -0
  27. {action0_req-0.3.0 → action0_req-0.3.1}/tests/action0/req/test_body.py +0 -0
  28. {action0_req-0.3.0 → action0_req-0.3.1}/tests/action0/req/test_init.py +0 -0
  29. {action0_req-0.3.0 → action0_req-0.3.1}/tests/action0/req/test_request.py +0 -0
  30. {action0_req-0.3.0 → action0_req-0.3.1}/tests/action0/req/test_response.py +0 -0
  31. {action0_req-0.3.0 → action0_req-0.3.1}/tests/action0/req/test_status.py +0 -0
  32. {action0_req-0.3.0 → action0_req-0.3.1}/tests/test_docs.py +0 -0
@@ -4,6 +4,35 @@ All notable changes to action0-req are listed here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the version
5
5
  numbers follow [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## 0.3.1 — 2026-12-02
8
+
9
+ ### Added
10
+
11
+ - `MultipartBody`: a `multipart/form-data` body (RFC 7578) as a body
12
+ producer. Fields are given as a mapping or as name/value pairs — text,
13
+ numbers, bytes or producers, a list for a field that occurs several
14
+ times; the parts are encoded as the body is read, and a producer part
15
+ (a file) is streamed. `content_type` is the header value a request
16
+ with the body needs, with the boundary; `content_length()` is known
17
+ when every part knows its own.
18
+ - `Part`: a field value with a filename, a content type or headers of
19
+ its own. `Part.file(path)` is a file on disk, streamed and readable
20
+ again; a part with a filename gets its content type guessed from it.
21
+
22
+ ### Changed
23
+
24
+ - **action0-url 0.2.2 is required** (was 0.2.1). It copies and renders
25
+ URLs faster, with the same results — which a request does for every
26
+ send; nothing else changes with it.
27
+ - Header lines are checked much faster, with the same rules and the same
28
+ errors. A field name is checked with one search instead of character
29
+ by character, and a line whose value is already a `str` skips the
30
+ handling of the other value forms. Building `Headers` from six lines
31
+ takes about a third of the time; an API client does that for every
32
+ response, where it was the costliest single step outside the network.
33
+ - `Headers()` and a `Request` or `Response` without headers no longer go
34
+ through the type checks for the forms headers can be given in.
35
+
7
36
  ## 0.3.0 — 2026-11-26
8
37
 
9
38
  ### Added
@@ -42,6 +42,7 @@ uv build # build sdist + wheel into dist/
42
42
  The modules under `src/action0/req/`:
43
43
 
44
44
  - `headers.py` — `Headers`: ordered, case-insensitive, multi-value aware mapping of header fields, internally a `list[tuple[str, str]]` of lines preserving the representation (order and casing) exactly. The `MutableMapping` view is single-value (last line per field, like `Params`); `get_all()`/`get_values()` (RFC 9110 comma-splitting)/`add()`/`set()`/`remove()`/`update()`/`as_lines()`/`as_dict()`/`as_str()` handle multiple lines. No underscore→dash normalization (header smuggling footgun). Names are compared by the private `_fold()`: ASCII letters lowercased, nothing else — deliberately not `casefold()`/`lower()`, which map lookalikes from outside ASCII (`Hoſt`, the Kelvin sign) onto ASCII letters. Lookups are answered from a lazily built index (`_fields()`: folded name → first-line name + values), dropped by every method that changes `_lines` — a class-level `_index = None` default keeps old pickles loading; `update()` merges in one pass and does not call `set()`. Every line goes in through the private `_lines()`, which refuses a CR, LF or NUL in a name or value, and a name that is empty or contains whitespace or a colon (`ValueError` — header injection/smuggling, `_check_name()`), a name that is not a str and a value that is not a str/int/float/bool, on its own or in a list (`TypeError` — bytes, `None`); the constructor raises a `TypeError` for what is no form of headers at all. `_check_safe()` (CR/LF/NUL) and `_check_token()` (additionally: not empty, no whitespace) are reused by `Request.as_str()`/`Response.as_str()` for the start line. A raw block is split at `\r\n`/`\n` only (never `str.splitlines()`), and a line with whitespace in its name is invalid. `get_values()` splits with the quote-aware `_split_elements()` (which also splits the `;` parameters of a Content-Type for `_charset()`). `__eq__` ignores field order and name casing but respects per-field line order, and is `False` (never raises) for a mapping that cannot be headers; `repr()`/`str()` redact the values of `Headers.secret_names` with `***` — only the wire rendering `as_str()` keeps them. `copy()` keeps the class and the instance dict (a `secret_names` set on the instance) without going through the constructor; requests and responses take headers over with the private `_own_headers()`, so a subclass survives. Also `Header`: `StrEnum` of the IANA HTTP field name registry (permanent + deprecated + provisional registrations, generated from the registry CSV, last compared on 2026-11-26) plus a block of unregistered de-facto `X-…` names.
45
+ - `multipart.py` — `multipart/form-data` (RFC 7578): `MultipartBody` is a `BodyProducer` over fields given as a mapping or as name/value pairs (text/numbers coerced like header values, bytes, producers, a list/tuple = the field several times), every value normalised to a `Part` (content + optional `filename`, `content_type`, further headers; `Part.file(path)` wraps a `FileBody`, so it is streamed and can be read again). The head of each part is encoded ONCE in the constructor (that also makes `content_length()` cheap — `None` as soon as one producer part does not know its length); `chunks()`/`achunks()` pass a producer part's chunks on, never collecting them. Names and filenames are escaped the HTML way (`"` → `%22`, CR → `%0D`, LF → `%0A`; non-ASCII as UTF-8, no `filename*`), extra part headers go through `Headers` (so they cannot start a line), `Content-Disposition`/`Content-Type` in them are refused. The boundary is 32 random hex digits unless given (validated per RFC 2046; quoted in `content_type` where needed) and the content is NOT searched for it. `parts` is public on purpose: action0-client looks at the parts to decide whether a body can be sent again. A test parses the output with the stdlib MIME parser.
45
46
  - `status.py` — `Status`: custom `IntEnum` of the IANA status code registry with `phrase` and `is_informational`/`is_success`/`is_redirection`/`is_client_error`/`is_server_error` properties. Deliberately not `http.HTTPStatus`: the stdlib's code list and category properties vary across 3.11–3.15. Two pre-RFC-9110 aliases (`PAYLOAD_TOO_LARGE`, `UNPROCESSABLE_ENTITY`).
46
47
  - `request.py` — `Method`: `StrEnum` of the RFC 9110 verbs + `PATCH` + `QUERY`. `Request`: `method` (a property uppercasing on every set, stored in `__dict__["method"]` so pickles from before it was a property still load), `url` (`action0.url.Url` — copied on ingestion by the constructor; a property like `method`: an assigned str is parsed, `None` gives an empty `Url`, a `Url` is taken as it is, anything else is a `TypeError`; `query=` kwarg replaces the URL's query like the `Url` constructor, except that `None` means "not given" and keeps it — deliberately, callers pass `query=None` for "no params"), `headers` (`Headers` — a property too: an assigned mapping/list/raw block/`None` is converted by the `Headers` constructor, a `Headers` instance is taken as it is), `body` (`bytes | str | BodyProducer | None`, stored as set; a `bytearray`/`memoryview` is a `TypeError` from every accessor — the private `_producer()`), `http_version`, `target` (explicit request target, `None` = derive the origin-form; for `*`, authority-form and absolute-form, which a URL cannot express; part of `copy()` and `__eq__`) and a `meta` dict (application metadata: never on the wire, excluded from `__eq__`, shallow-copied by `copy()`; the constructor copies the given mapping) as plain attributes. Typed body accessors `body_bytes()`/`body_str()`/`body_producer()` convert between the three forms using the Content-Type charset (default utf-8); `abody_bytes()`/`abody_str()` read a producer via `achunks()`. `close()`/`aclose()` + sync/async context manager as on `Response` (shared helpers in `body.py`). `copy(**overrides)` (own `Url`/`Headers`, same class; a `BodyProducer` body is shared; goes through the constructor and then takes over whatever else is in the instance dict — a `secret_params` set on the instance), part-wise `__eq__` (body compared as set), `repr()` redacts via `Url.__repr__` plus the values of the `secret_params` query parameters, also in a fragment written like a query (done on the rendered string by `_redact_query()` — setting a param on the Url would respell the query) and omits headers/body, `from_str(text, scheme=None)` parses what `as_str()` renders (URL from target + `Host`, no scheme assumed; a `Host` that is more than host[:port] and a second `Host` line are a `ValueError`; a target the Url would not reproduce is kept as `target`, so the text round-trips — but for the documented normalizations: the method is uppercased, and an absolute-form/authority-form request without `Host` is rendered with the derived one; body after the blank line as `str`), `as_str(include_body=False, separator="\r\n")` renders the wire format with origin-form target and derived `Host` (secrets included; a `BodyProducer` is never consumed — placeholder; bytes are decoded with `errors="replace"` and an unknown charset falls back to utf-8, a rendering never raises over the body; a method, target or version that is empty or contains a CR/LF/NUL or any other whitespace is a `ValueError`). Target and `Host` are the `Url`'s own `request_target` and `raw_authority` (action0-url 0.2.1), never rebuilt from the decoded `url.path`/`url.authority`: the target is the URL's spelling character for character (escapes of a signed URL survive), always an absolute path and without the prefixes (`/.`, `./`) a URL without a host needs to round-trip, and the `Host` is IDNA-encoded.
47
48
  - `body.py` — `BodyProducer`: runtime-checkable `Protocol` for streaming bodies: `content_length()` (`None` = unknown), sync `chunks()`, async `achunks()`, `as_bytes()`. Implementations: `BytesBody` (in-memory, single chunk; `__eq__`/`__hash__` by content; refuses a str), `FileBody` (path or open binary file object + `chunk_size`; paths open freshly per iteration → re-iterable, seekable file objects are rewound per iteration and never closed, non-seekable ones are single-use with unknown length; `content_length()` is `None` for a non-seekable file object and for a path that is not a regular file; `achunks()` does all file ops in a worker thread via the private `_in_thread` helper: the loop's default executor through `loop.run_in_executor` with a copied context — what `asyncio.to_thread` does, but a plain future and not a task, so cancelling all tasks of the loop cannot make the wait end while the function still runs —, or — when there is no running asyncio loop but `trio` is in `sys.modules` — `trio.to_thread.run_sync`; trio is never imported — it is a dev dependency for the tests only. Three dispatch variants: `_in_thread` never abandons a started call — on asyncio it waits for it through cancellations and re-raises afterwards (the result is lost then, so code opening a file in a thread records the handle itself); `_in_thread_shielded`, for cleanup (closing a file, the final flush), on trio also starts in a scope that is cancelled already; `_in_thread_abandonable` leaves the thread behind on cancellation — on asyncio a daemon thread (`_in_daemon_thread`, running the call in a copy of the caller's context like the pool does) instead of the loop's pool, taken from the private `_DaemonThreads` cache (an idle thread waits 10 s for the next call, so a pipe read chunk by chunk does not start a thread per chunk; a job returns its report function, which the thread calls only after it has put itself back — otherwise the woken consumer would find no idle thread), on trio `abandon_on_cancel` (`cancellable` before 0.23; the keyword is looked up once per `run_sync`, `_abandon_keyword()`) with the private no-op limiter `_UNLIMITED` — trio's default limiter keeps the place of an abandoned thread until it returns, and stalled reads would use it up. `FileBody.achunks()` uses it only for what may block for good: a path that is not a regular file (open and reads; the private `_OwnedFile` lets the abandoned call close the file) and a non-seekable file object. Regular files and seekable file objects are read with `_in_thread`, so a cancelled read never moves the position under the next reader. For `Response.body_file()` a `FileBody` hands out its seekable file via the private `_file_view()`: the given file object, or for the path of a regular file a newly opened file per call, tracked (under the module-level `_VIEWS_LOCK` — `abody_file()` calls it in worker threads, and a lock on the instance would cost the body its picklability) and closed by its public `close()`; `None` (→ spooled) for non-seekable/non-regular sources and for subclasses overriding `chunks()`/`achunks()`/`as_bytes()`), `IterableBody` (wraps `Iterable[bytes]`, unknown length; the single-use bookkeeping is the private base `_SingleUse`, shared with `AsyncIterableBody`; a source that is an `Iterator` is single-use: a second read, or a read after `close()`, raises a `RuntimeError` that explains it instead of yielding nothing, and a read that is under way when the body is closed raises at its end (`_cut`) — between two chunks when `close()` closes the generator, or inside the running generator when the callback takes away what it reads and it then returns as if done; a `close()` coming from the generator itself (`_called_from()` walks the frames) is its regular end; a generator that is running is not closed (`_close_generator()`, which also takes the race with a worker thread entering it for "running"); `threaded=True` makes `achunks()` fetch every chunk with `_in_thread_abandonable` and close in a worker thread, the default reads on the event loop; optional `close=` callback run exactly once — after consumption, on abandoned iteration or on `close()` — because a never-started generator's `finally` does not run; `close()` also closes a generator source — generators only, other iterables with a `close()` are left alone, and not a generator that is running right now: then the callback is what releases, and without one `close()` raises `RuntimeError`; `achunks()` closes the generator a re-iterable source made for the read, `_close_after_read()`), `AsyncIterableBody` (wraps `AsyncIterable[bytes]`, async-only: sync `chunks()`/`as_bytes()` raise `RuntimeError`; single-use like `IterableBody` for an `AsyncIterator` source; `aclose=` callback/`aclose()` as the async twin; `aclose()` also closes an async generator source unless another task is running in it (then as in `IterableBody`: callback and `_cut`, or `RuntimeError` without one); `achunks()` closes the async generator a re-iterable source made for the read; the sync `close()` is a no-op unless the callback is still pending or a started async generator — the source, or that of a read — is still open — then it raises `RuntimeError`), `SpooledBody` (written first, read afterwards: a `SpooledTemporaryFile` with its automatic rollover turned off — the class rolls over itself once `max_memory` is exceeded, so `awrite()` can stay inline while in memory and move the rollover and all later writes into a worker thread; the private `_Spool` subclass tracks the rollover, refuses one on a closed spool and closes itself when one fails — the stdlib has swapped the files by then, and a half-moved spool would hand out part of the data; every reader has a position of its own — `chunks()`/`achunks()` track an offset, `file()` returns a new read-only `io.BufferedReader` over the private `_SpoolView` per call (closing it leaves the body alone, no `fileno()`) — and a lock makes each seek+read/write on the one file object a single step, so overlapping readers are safe (`achunks()` reads inline only via the non-waiting `_read_inline`, never blocking the loop on the lock; a reader ends where the data ends — at `_size`, the end of the last complete write, not at the end of the file, where a failed write may have left a part —, so a body is to be read once complete); `close()`/`aclose()`/context managers remove the temp file). `close()`/`aclose()` are deliberately NOT part of the `BodyProducer` protocol (duck-typed by `Response.close()`), so third-party producers stay valid. `save_body()`/`asave_body()` copy a body into a path (`append=` for Range-resumed downloads) or file object — a path is opened only after the body's first chunk, so an unreadable body leaves the file untouched, and `_write_all` completes the short writes of a raw target (the remainder is passed as a `memoryview`; `None` from an `io.RawIOBase` is non-blocking "nothing written" → `BlockingIOError`; from any other file-like it counts as written); a generator of chunks is closed on the way out, so a failed write does not leave the stream half-read; the async one opens the file and writes the first chunk in one thread call, batches small chunks to 64 KiB per thread hop (the batch is taken over inside the thread, so a flush trio refuses to start loses nothing) and flushes what has arrived when the stream breaks off. Also the `BodyTypes` alias and the private helpers shared by `Request` and `Response`: conversion (`_charset`, `_body_bytes`/`_body_str`/`_body_producer`, the async `_abody_bytes`/`_abody_str` over `_read_all`, `_rendered_body`, which falls back to utf-8 for every charset Python cannot decode with; `_producer`, the `TypeError` for a `bytearray`/`memoryview` body) and closing (`_close_body`/`_aclose_body`, `_close_on_exit`/`_aclose_on_exit`) — the classes keep their own thin, documented accessor methods.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: action0-req
3
- Version: 0.3.0
3
+ Version: 0.3.1
4
4
  Summary: Library for representing, creating and manipulating HTTP requests and responses
5
5
  Project-URL: Homepage, https://github.com/LaughInJar/action0-req
6
6
  Project-URL: Documentation, https://laughinjar.github.io/action0-req/
@@ -23,7 +23,7 @@ Classifier: Topic :: Internet :: WWW/HTTP
23
23
  Classifier: Topic :: Software Development :: Libraries
24
24
  Classifier: Typing :: Typed
25
25
  Requires-Python: >=3.11
26
- Requires-Dist: action0-url<0.3,>=0.2.1
26
+ Requires-Dist: action0-url<0.3,>=0.2.2
27
27
  Description-Content-Type: text/markdown
28
28
 
29
29
  # Action0-Req
@@ -177,6 +177,21 @@ with Response(200, body=IterableBody([compressed[:8], compressed[8:]])) as resp:
177
177
  print(resp.body_bytes() == compressed) # True
178
178
  ```
179
179
 
180
+ A form with files is a `MultipartBody`; a file part is streamed from
181
+ disk when the body is sent:
182
+
183
+ ```python
184
+ from action0.req import MultipartBody, Part, Request
185
+
186
+ body = MultipartBody({"title": "Quarterly report", "file": Part.file("reports/2026-q3.pdf")})
187
+ request = Request(
188
+ "https://api.example.com/documents",
189
+ "POST",
190
+ headers={"Content-Type": body.content_type}, # multipart/form-data; boundary=...
191
+ body=body,
192
+ )
193
+ ```
194
+
180
195
  ## Development
181
196
 
182
197
  The project is managed with [uv](https://docs.astral.sh/uv/); `uv run`
@@ -149,6 +149,21 @@ with Response(200, body=IterableBody([compressed[:8], compressed[8:]])) as resp:
149
149
  print(resp.body_bytes() == compressed) # True
150
150
  ```
151
151
 
152
+ A form with files is a `MultipartBody`; a file part is streamed from
153
+ disk when the body is sent:
154
+
155
+ ```python
156
+ from action0.req import MultipartBody, Part, Request
157
+
158
+ body = MultipartBody({"title": "Quarterly report", "file": Part.file("reports/2026-q3.pdf")})
159
+ request = Request(
160
+ "https://api.example.com/documents",
161
+ "POST",
162
+ headers={"Content-Type": body.content_type}, # multipart/form-data; boundary=...
163
+ body=body,
164
+ )
165
+ ```
166
+
152
167
  ## Development
153
168
 
154
169
  The project is managed with [uv](https://docs.astral.sh/uv/); `uv run`
@@ -44,6 +44,13 @@ from action0.req import BodyTypes, HeaderTypes, HeaderValue # the type aliases
44
44
  :undoc-members:
45
45
  ```
46
46
 
47
+ ## Multipart bodies
48
+
49
+ ```{eval-rst}
50
+ .. automodule:: action0.req.multipart
51
+ :members:
52
+ ```
53
+
47
54
  ## Status
48
55
 
49
56
  ```{eval-rst}
@@ -442,6 +442,78 @@ print(req.as_str(include_body=True, separator="\n"))
442
442
  # <BytesBody>
443
443
  ```
444
444
 
445
+ ### Forms with files: multipart
446
+
447
+ {py:class}`~action0.req.multipart.MultipartBody` encodes a
448
+ `multipart/form-data` body — what an HTML form with a file input sends,
449
+ and what most upload endpoints expect. Fields are given as a mapping or
450
+ as name/value pairs; a value is text, a number, bytes or a producer,
451
+ and a list sends the field once per element:
452
+
453
+ ```python
454
+ from action0.req import MultipartBody
455
+
456
+ body = MultipartBody({"title": "Quarterly report", "tag": ["finance", 2026]}, boundary="frontier")
457
+ print(body.content_type)
458
+ # multipart/form-data; boundary=frontier
459
+ print(body.as_bytes().decode().replace("\r\n", "\n"), end="")
460
+ # --frontier
461
+ # Content-Disposition: form-data; name="title"
462
+ #
463
+ # Quarterly report
464
+ # --frontier
465
+ # Content-Disposition: form-data; name="tag"
466
+ #
467
+ # finance
468
+ # --frontier
469
+ # Content-Disposition: form-data; name="tag"
470
+ #
471
+ # 2026
472
+ # --frontier--
473
+ ```
474
+
475
+ A file — or any value that needs a filename, a content type or headers
476
+ of its own — is a {py:class}`~action0.req.multipart.Part`. The request
477
+ gets the body's `content_type`, which names the boundary:
478
+
479
+ ```python
480
+ from action0.req import MultipartBody, Part, Request
481
+
482
+ body = MultipartBody(
483
+ [
484
+ ("title", "Quarterly report"),
485
+ ("file", Part.file("reports/2026-q3.pdf")), # streamed from disk
486
+ ("meta", Part('{"pages": 12}', content_type="application/json")),
487
+ ]
488
+ )
489
+ request = Request(
490
+ "https://api.example.com/documents",
491
+ "POST",
492
+ headers={"Content-Type": body.content_type},
493
+ body=body,
494
+ )
495
+ ```
496
+
497
+ - `Part.file(path)` streams the file when the body is sent and announces
498
+ the last component of the path as the filename. A part with a
499
+ filename gets a content type guessed from it
500
+ (`application/octet-stream` if the ending says nothing) unless you
501
+ give one.
502
+ - The body is a {py:class}`~action0.req.body.BodyProducer`: `chunks()`
503
+ and `achunks()` pass the content of a producer part on chunk by
504
+ chunk, so a large file is never in memory as a whole.
505
+ `content_length()` is known whenever every part knows its own.
506
+ - The boundary is 32 random hex digits unless you set one. The content
507
+ is not searched for it (a stream could not be), so a boundary of your
508
+ own must be one that does not occur in the parts.
509
+ - A field name or a filename cannot break out of its header: the
510
+ characters that would end the quoted value or the line are
511
+ percent-encoded, as browsers do it; text beyond ASCII is sent in
512
+ UTF-8.
513
+ - Whether the body can be read again — for a retry — depends on its
514
+ parts: text, bytes and files given by their path can, a part
515
+ streaming from a generator cannot.
516
+
445
517
  ## Streaming bodies
446
518
 
447
519
  Besides {py:class}`~action0.req.body.BytesBody` there are three
@@ -10,10 +10,11 @@ license = "MIT"
10
10
  license-files = ["LICENSE"]
11
11
  requires-python = ">=3.11"
12
12
  dependencies = [
13
- # 0.2.1 for Url.request_target and Url.raw_authority. Capped below the
14
- # next minor: action0-url is 0.x, where a minor release may change
15
- # behaviour (as 0.2.0 did)
16
- "action0-url>=0.2.1,<0.3",
13
+ # 0.2.1 for Url.request_target and Url.raw_authority, 0.2.2 for its
14
+ # faster copying and rendering (a request copies and renders its URL
15
+ # every time). Capped below the next minor: action0-url is 0.x, where
16
+ # a minor release may change behaviour (as 0.2.0 did)
17
+ "action0-url>=0.2.2,<0.3",
17
18
  ]
18
19
  keywords = ["http", "request", "response", "headers", "status", "manipulation"]
19
20
  classifiers = [
@@ -11,12 +11,14 @@ from .headers import Header
11
11
  from .headers import Headers
12
12
  from .headers import HeaderTypes
13
13
  from .headers import HeaderValue
14
+ from .multipart import MultipartBody
15
+ from .multipart import Part
14
16
  from .request import Method
15
17
  from .request import Request
16
18
  from .response import Response
17
19
  from .status import Status
18
20
 
19
- __version__: str = "0.3.0"
21
+ __version__: str = "0.3.1"
20
22
 
21
23
  __all__ = [
22
24
  "AsyncIterableBody",
@@ -30,6 +32,8 @@ __all__ = [
30
32
  "Headers",
31
33
  "IterableBody",
32
34
  "Method",
35
+ "MultipartBody",
36
+ "Part",
33
37
  "Request",
34
38
  "Response",
35
39
  "SpooledBody",
@@ -35,6 +35,16 @@ _LINE_END = re.compile(r"\r?\n")
35
35
  # (or, for NUL, the string) on the wire and let a value smuggle in a field
36
36
  _UNSAFE = re.compile(r"[\r\n\x00]")
37
37
 
38
+ # What a field name must not contain, in one pattern: whitespace of any
39
+ # kind (which includes CR and LF), a NUL and a colon. "\s" is exactly what
40
+ # str.isspace() calls whitespace (a test compares the two for every code
41
+ # point). One search answers the usual question — is this name fine? — for
42
+ # the whole name at once; looking at it character by character in Python
43
+ # made validating the header lines the most expensive part of building a
44
+ # request or a response. _check_name still works out WHICH rule a bad name
45
+ # breaks.
46
+ _BAD_NAME = re.compile(r"[\s\x00:]")
47
+
38
48
  _UNSAFE_NAMES = {"\r": "a carriage return", "\n": "a line feed", "\x00": "a NUL character"}
39
49
 
40
50
  _ASCII_LOWER = str.maketrans(string.ascii_uppercase, string.ascii_lowercase)
@@ -105,6 +115,9 @@ def _check_name(name: str) -> None:
105
115
  :raises ValueError: if the name is empty or contains a CR, an LF, a
106
116
  NUL, any other whitespace or a colon
107
117
  """
118
+ if name and _BAD_NAME.search(name) is None:
119
+ # nothing wrong with it: the common case, settled by one search
120
+ return
108
121
  if not name:
109
122
  raise ValueError("a header name must not be empty")
110
123
  _check_safe(name, "header name")
@@ -185,6 +198,18 @@ def _lines(name: str, value_s: Union[HeaderValue, Iterable[HeaderValue]]) -> lis
185
198
  colon; if the name or a value contains a CR, an
186
199
  LF or a NUL
187
200
  """
201
+ if isinstance(name, str) and type(value_s) is str:
202
+ # The common case — one line, its value already text — with the
203
+ # same checks as below, but without the detours for the other
204
+ # forms a value can have (numbers, bools, lists of them). Every
205
+ # header line of every request and response comes through here,
206
+ # so those detours added up to about a third of the time spent
207
+ # on a request outside the network.
208
+ if not name or _BAD_NAME.search(name) is not None:
209
+ _check_name(name) # raises, naming the rule that is broken
210
+ if _UNSAFE.search(value_s) is not None:
211
+ _check_safe(value_s, f"value of the header {name!r}") # raises
212
+ return [(name, value_s)]
188
213
  if not isinstance(name, str):
189
214
  raise TypeError(f"a header name must be a str, got {type(name).__name__}: {name!r}")
190
215
  _check_name(name)
@@ -327,7 +352,12 @@ class Headers(MutableMapping[str, str]):
327
352
  """
328
353
  self._lines: list[tuple[str, str]] = []
329
354
 
330
- if isinstance(headers, Headers):
355
+ if headers is None:
356
+ # asked first: every request and response without headers of
357
+ # its own would otherwise go through all the type checks below
358
+ pass
359
+
360
+ elif isinstance(headers, Headers):
331
361
  self._lines = list(headers._lines)
332
362
 
333
363
  elif isinstance(headers, str):
@@ -361,7 +391,7 @@ class Headers(MutableMapping[str, str]):
361
391
  name, value_s = item
362
392
  self.add(name, value_s)
363
393
 
364
- elif headers is not None:
394
+ else:
365
395
  raise TypeError(
366
396
  "headers must be a raw header block, a mapping, an iterable of "
367
397
  f"(name, value) tuples or a Headers instance, got {type(headers).__name__}"