action0-req 0.2.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.
- {action0_req-0.2.0 → action0_req-0.3.1}/.github/workflows/release.yml +19 -0
- action0_req-0.3.1/CHANGELOG.md +376 -0
- action0_req-0.3.1/CLAUDE.md +57 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/PKG-INFO +60 -8
- {action0_req-0.2.0 → action0_req-0.3.1}/README.md +58 -6
- {action0_req-0.2.0 → action0_req-0.3.1}/docs/api.md +8 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/docs/conf.py +4 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/docs/index.md +9 -7
- {action0_req-0.2.0 → action0_req-0.3.1}/docs/usage.md +482 -30
- {action0_req-0.2.0 → action0_req-0.3.1}/pyproject.toml +5 -4
- {action0_req-0.2.0 → action0_req-0.3.1}/src/action0/req/__init__.py +11 -1
- {action0_req-0.2.0 → action0_req-0.3.1}/src/action0/req/body.py +836 -105
- {action0_req-0.2.0 → action0_req-0.3.1}/src/action0/req/headers.py +410 -75
- action0_req-0.3.1/src/action0/req/multipart.py +431 -0
- action0_req-0.3.1/src/action0/req/request.py +749 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/src/action0/req/response.py +339 -64
- {action0_req-0.2.0 → action0_req-0.3.1}/src/action0/req/status.py +1 -1
- {action0_req-0.2.0 → action0_req-0.3.1}/tests/action0/req/test_body.py +1509 -11
- action0_req-0.3.1/tests/action0/req/test_headers.py +1147 -0
- action0_req-0.3.1/tests/action0/req/test_multipart.py +434 -0
- action0_req-0.3.1/tests/action0/req/test_request.py +1482 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/tests/action0/req/test_response.py +803 -4
- action0_req-0.3.1/tests/test_docs.py +104 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/uv.lock +4 -4
- action0_req-0.2.0/CHANGELOG.md +0 -70
- action0_req-0.2.0/CLAUDE.md +0 -56
- action0_req-0.2.0/src/action0/req/request.py +0 -261
- action0_req-0.2.0/tests/action0/req/test_headers.py +0 -386
- action0_req-0.2.0/tests/action0/req/test_request.py +0 -337
- {action0_req-0.2.0 → action0_req-0.3.1}/.github/workflows/ci.yml +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/.gitignore +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/.python-version +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/LICENSE +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/docs/changelog.md +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/src/action0/req/py.typed +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/tests/action0/req/test_init.py +0 -0
- {action0_req-0.2.0 → action0_req-0.3.1}/tests/action0/req/test_status.py +0 -0
|
@@ -10,6 +10,17 @@ jobs:
|
|
|
10
10
|
runs-on: ubuntu-latest
|
|
11
11
|
steps:
|
|
12
12
|
- uses: actions/checkout@v7
|
|
13
|
+
with:
|
|
14
|
+
# the whole history: the tag is checked against main below
|
|
15
|
+
fetch-depth: 0
|
|
16
|
+
|
|
17
|
+
- name: Check that the tag is on main
|
|
18
|
+
run: |
|
|
19
|
+
git fetch origin main
|
|
20
|
+
if ! git merge-base --is-ancestor "$GITHUB_SHA" origin/main; then
|
|
21
|
+
echo "tag $GITHUB_REF_NAME points at $GITHUB_SHA, which is not on main" >&2
|
|
22
|
+
exit 1
|
|
23
|
+
fi
|
|
13
24
|
|
|
14
25
|
- name: Install uv
|
|
15
26
|
uses: astral-sh/setup-uv@v10.0.1
|
|
@@ -34,6 +45,14 @@ jobs:
|
|
|
34
45
|
exit 1
|
|
35
46
|
fi
|
|
36
47
|
|
|
48
|
+
- name: Check that the changelog has a section for the version
|
|
49
|
+
run: |
|
|
50
|
+
version="${GITHUB_REF_NAME#v}"
|
|
51
|
+
if ! grep -qE "^## ${version//./\\.} — [0-9]{4}-[0-9]{2}-[0-9]{2}$" CHANGELOG.md; then
|
|
52
|
+
echo "CHANGELOG.md has no \"## $version — YYYY-MM-DD\" section" >&2
|
|
53
|
+
exit 1
|
|
54
|
+
fi
|
|
55
|
+
|
|
37
56
|
- name: Build sdist and wheel
|
|
38
57
|
run: uv build
|
|
39
58
|
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to action0-req are listed here. The format follows
|
|
4
|
+
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the version
|
|
5
|
+
numbers follow [Semantic Versioning](https://semver.org/).
|
|
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
|
+
|
|
36
|
+
## 0.3.0 — 2026-11-26
|
|
37
|
+
|
|
38
|
+
### Added
|
|
39
|
+
|
|
40
|
+
- `Request.target`: the request target to render instead of the
|
|
41
|
+
origin-form derived from the URL — `"*"` for a server-wide `OPTIONS`,
|
|
42
|
+
`"host:port"` for `CONNECT`, an absolute URL for a request to a proxy.
|
|
43
|
+
Also a constructor keyword; part of `copy()` and of equality.
|
|
44
|
+
- `Request.from_str()` and `Response.from_str()`: parse the text that
|
|
45
|
+
`as_str()` renders — start line, header lines and, behind a blank
|
|
46
|
+
line, the body (as a `str`). The request URL is put together from the
|
|
47
|
+
target and the `Host` header, with the `scheme` you pass.
|
|
48
|
+
- `abody_bytes()` and `abody_str()` on `Request` and `Response`, and
|
|
49
|
+
`Response.abody_file()`: the asynchronous twins of the body accessors.
|
|
50
|
+
They read a producer through `achunks()`, which makes an
|
|
51
|
+
`AsyncIterableBody` readable as a whole and as a file, and keeps a
|
|
52
|
+
file-backed body from blocking the event loop.
|
|
53
|
+
- `Response.body_file()` takes `max_memory` and `dir` for the
|
|
54
|
+
`SpooledBody` a stream is read into.
|
|
55
|
+
- `Request.close()` and `Request.aclose()`; a request is a sync and
|
|
56
|
+
async context manager like a response, for a body that holds a
|
|
57
|
+
resource and was never sent.
|
|
58
|
+
- `IterableBody(..., threaded=True)`: `achunks()` fetches every chunk in
|
|
59
|
+
a worker thread, for an iterable that blocks while it produces one.
|
|
60
|
+
Without it the iterable runs on the event loop, as before — which is
|
|
61
|
+
now documented.
|
|
62
|
+
- `Request.secret_params`: the names of the query parameters whose
|
|
63
|
+
values `repr(request)` shows as `***` (`api_key`, `token`,
|
|
64
|
+
`signature`, …), overridable like `Headers.secret_names`.
|
|
65
|
+
- `BytesBody` compares by its bytes (and is hashable), so requests and
|
|
66
|
+
responses with equal `BytesBody` bodies are equal. All producers have
|
|
67
|
+
a `repr()` that says what they are without showing their data.
|
|
68
|
+
- `BodyTypes`, `HeaderTypes` and `HeaderValue` are importable from the
|
|
69
|
+
package root.
|
|
70
|
+
- `Header.CONNECT_UDP_BIND`, `Header.NO_VARY_SEARCH` and
|
|
71
|
+
`Header.PROXY_PUBLIC_ADDRESS`: the field names registered since the
|
|
72
|
+
last snapshot of the IANA registry (now as of 2026-11-26).
|
|
73
|
+
|
|
74
|
+
### Changed
|
|
75
|
+
|
|
76
|
+
Behaviour that code may rely on:
|
|
77
|
+
|
|
78
|
+
- **A streamed body can be read once, and says so.** Reading an
|
|
79
|
+
`IterableBody` or `AsyncIterableBody` over a generator (or any other
|
|
80
|
+
iterator) a second time, or after it has been closed, raises a
|
|
81
|
+
`RuntimeError` explaining what happened. It used to return nothing,
|
|
82
|
+
which passed for an empty body — `Response.save_body()` after
|
|
83
|
+
`body_bytes()` truncated the file. A read that is between two chunks
|
|
84
|
+
when the body is closed raises as well instead of ending quietly.
|
|
85
|
+
Bodies over a list are re-readable as before; for a response,
|
|
86
|
+
`body_file()` / `abody_file()` keep a stream readable.
|
|
87
|
+
- **Header names and values must not contain a CR, an LF or a NUL**:
|
|
88
|
+
`Headers` raises a `ValueError` for them, whichever way they come in.
|
|
89
|
+
`Request.as_str()` and `Response.as_str()` do the same for the method,
|
|
90
|
+
the target, the HTTP version and the reason phrase.
|
|
91
|
+
- **A raw header block is split at `\r\n` and `\n` only** (it was
|
|
92
|
+
`str.splitlines()`, which also splits at `\x0b`, `\x0c`, `\x85`,
|
|
93
|
+
U+2028, … and a lone `\r`), and a line whose name contains whitespace
|
|
94
|
+
— `Name : value`, a folded line, a request line — is a `ValueError`.
|
|
95
|
+
- **Bytes are not header values**: `Headers({"X": b"ab"})` raises a
|
|
96
|
+
`TypeError` (it produced the lines `X: 97` and `X: 98`), and so does a
|
|
97
|
+
string where a name/value tuple is expected (`Headers(["ab"])`).
|
|
98
|
+
- **`Response.as_str()` keeps the space behind the status code** when
|
|
99
|
+
there is no phrase: `"HTTP/1.1 599 "`, as the grammar of the status
|
|
100
|
+
line requires (was `"HTTP/1.1 599"`).
|
|
101
|
+
- **`Response.status` must be an int**: anything else raises a
|
|
102
|
+
`TypeError` when it is set.
|
|
103
|
+
- **`FileBody.content_length()` is `None` for a path that is not a
|
|
104
|
+
regular file** (a named pipe, a device); it was the `0` of the
|
|
105
|
+
directory entry.
|
|
106
|
+
- `Request.method` is uppercased whenever it is set, not only by the
|
|
107
|
+
constructor.
|
|
108
|
+
- `repr(request)` shows the values of the `Request.secret_params` query
|
|
109
|
+
parameters as `***`.
|
|
110
|
+
- `Headers.get_values()` no longer splits at a comma inside a quoted
|
|
111
|
+
string (`private="a, b"`).
|
|
112
|
+
- `Headers.copy()` returns an instance of the same class and keeps a
|
|
113
|
+
`secret_names` set on the instance; `Request`/`Response` keep a
|
|
114
|
+
`Headers` subclass they are given, and their `copy()` returns an
|
|
115
|
+
instance of their own class.
|
|
116
|
+
- A `SpooledBody` whose data cannot be moved to the temporary file is
|
|
117
|
+
closed (see Fixed).
|
|
118
|
+
- **Header names are matched by their ASCII letters only**, as HTTP
|
|
119
|
+
matches them. They were compared with `str.casefold()`, which also
|
|
120
|
+
maps characters from outside ASCII onto ASCII letters: `Hoſt` (U+017F)
|
|
121
|
+
was the `Host` header and `Coo\u212Aie` (the Kelvin sign) the `Cookie`
|
|
122
|
+
header here, and for no other party. Such a name is a field of its own
|
|
123
|
+
now — in lookups, in equality, in `Request.from_str()` (which took the
|
|
124
|
+
host of the URL from it) and for the `Host` that `Request.as_str()`
|
|
125
|
+
derives.
|
|
126
|
+
- **A header name must be a name**: an empty one, one with whitespace
|
|
127
|
+
(`"Transfer-Encoding "`, rendered as the request smuggling line
|
|
128
|
+
`Transfer-Encoding : chunked`) and one with a colon raise a
|
|
129
|
+
`ValueError` in `add()`, `set()`, `update()` and the constructor. The
|
|
130
|
+
parser of a raw header block refused them already.
|
|
131
|
+
- **A header value in a list is held to the same types as one on its
|
|
132
|
+
own**: a `str`, an `int`, a `float` or a `bool`. Anything else raises
|
|
133
|
+
a `TypeError`; it was turned into its `str()`, which sent a `None` in
|
|
134
|
+
a list as the header value `None`. `Headers(5)` — something that is no
|
|
135
|
+
form of headers at all — raises a `TypeError` as well instead of
|
|
136
|
+
giving empty headers.
|
|
137
|
+
- **`Request.as_str()` and `Response.as_str()` refuse a method, target
|
|
138
|
+
or HTTP version that is empty or contains whitespace** (`ValueError`):
|
|
139
|
+
the parts of a start line are separated by single spaces, and
|
|
140
|
+
`Request(url, target="/a b HTTP/1.0")` rendered a request line with a
|
|
141
|
+
target and a version of the caller's choosing.
|
|
142
|
+
- **`Request.from_str()` refuses a `Host` header that is more than a
|
|
143
|
+
host and a port, and more than one `Host` line** (`ValueError`). The
|
|
144
|
+
value was put in front of the target unchecked, so `Host:
|
|
145
|
+
trusted.com@evil.com` gave a URL with the host `evil.com`, and `Host:
|
|
146
|
+
e.com/evil?x` one with another path and query; of two lines the last
|
|
147
|
+
one won.
|
|
148
|
+
- **`Response.from_str()` keeps a missing phrase missing**: the `reason`
|
|
149
|
+
of a response parsed from `HTTP/1.1 200 ` (or `HTTP/2 200`) is `""`,
|
|
150
|
+
not `None`, so `as_str()` no longer writes the registry's `OK` behind
|
|
151
|
+
a status line that had no phrase, and `phrase` is empty. `None` still
|
|
152
|
+
means "not known" and falls back to the registry.
|
|
153
|
+
- **`Response.status` refuses a `bool`** (`TypeError`): `Response(True)`
|
|
154
|
+
was the status `1` and rendered as `HTTP/1.1 True `. The status of an
|
|
155
|
+
enum that is an int but not a `Status` is written as its number
|
|
156
|
+
(`HTTP/1.1 S.OK OK` before).
|
|
157
|
+
- **`url` and `headers` convert what is assigned to them**:
|
|
158
|
+
`request.url = "https://…"` gives a `Url`, `response.headers = {…}`
|
|
159
|
+
gives `Headers` — a dict there made every lookup case-sensitive, so
|
|
160
|
+
the charset was not found and `as_str()` failed. A `Url` or `Headers`
|
|
161
|
+
instance is taken as it is; anything that is neither raises.
|
|
162
|
+
- **A `bytearray` or `memoryview` body raises a `TypeError`** from the
|
|
163
|
+
body accessors, `as_str(include_body=True)`, `body_file()` and
|
|
164
|
+
`save_body()` that says to convert it; it was an `AttributeError`
|
|
165
|
+
about a missing method.
|
|
166
|
+
- `Request.copy()` and `Response.copy()` take along what has been set on
|
|
167
|
+
the instance besides the constructor arguments (see Fixed).
|
|
168
|
+
- `repr(request)` redacts the `Request.secret_params` in a fragment
|
|
169
|
+
that is written like a query as well (`#access_token=…`).
|
|
170
|
+
- `Headers.update()` no longer goes through `set()` for every field; a
|
|
171
|
+
subclass overriding `set()` to see every change has to override
|
|
172
|
+
`update()` too.
|
|
173
|
+
|
|
174
|
+
And from the dependency:
|
|
175
|
+
|
|
176
|
+
- **action0-url 0.2.1 is required** (was 0.1.0), and the requirement is
|
|
177
|
+
capped below 0.3: a minor release of a 0.x package may change
|
|
178
|
+
behaviour, as 0.2.0 did. (0.2.1 adds `Url.request_target` and
|
|
179
|
+
`Url.raw_authority`, which `Request.as_str()` takes the request target
|
|
180
|
+
and the `Host` header from; it changes nothing else.) The changes of
|
|
181
|
+
0.2.0 show through wherever a request has a URL; see the
|
|
182
|
+
[action0-url changelog](https://github.com/LaughInJar/action0-url/blob/main/CHANGELOG.md)
|
|
183
|
+
for all of them. What you will notice in requests:
|
|
184
|
+
- **No default scheme.** `Request("example.com/items")` used to become
|
|
185
|
+
`https:example.com/items`; now it is the relative path it is written
|
|
186
|
+
as. Write the scheme: `Request("https://example.com/items")`.
|
|
187
|
+
- **The URL is kept as it is written.** Percent escapes (`%2F`, `%7E`,
|
|
188
|
+
escapes that are not valid UTF-8) and the spelling of the query
|
|
189
|
+
(`?flag`, `%20`) are no longer decoded and re-encoded, so
|
|
190
|
+
`request.url.as_str()` shows a signed URL unchanged — and
|
|
191
|
+
`repr(request)` does too, apart from the values it redacts.
|
|
192
|
+
- **Requests are equal when their URLs are equivalent:** `%7E` equals
|
|
193
|
+
`~`, but `/a%2Fb` no longer equals `/a/b`.
|
|
194
|
+
- **Query parameter values** have to be strings, ints, floats or bools
|
|
195
|
+
(or an iterable of those): bytes, a `Decimal` or a `date` in
|
|
196
|
+
`query=` raise a `TypeError` — convert them with `str()`.
|
|
197
|
+
- `Request.as_str()` always writes an absolute path as target: a request
|
|
198
|
+
with a relative path and no host (`Request("items/5")`) is rendered as
|
|
199
|
+
`GET /items/5`, was `GET items/5`.
|
|
200
|
+
- `Request(url, query=None)` keeps the query of the URL, as before. This
|
|
201
|
+
now differs from `Url(url, query=None)`, which removes it since
|
|
202
|
+
action0-url 0.2.0; pass an empty mapping to remove the query.
|
|
203
|
+
|
|
204
|
+
### Fixed
|
|
205
|
+
|
|
206
|
+
- `as_str(include_body=True)` raised for a body that is not text in the
|
|
207
|
+
Content-Type charset (a compressed body: `UnicodeDecodeError`) or
|
|
208
|
+
whose charset Python does not know (`LookupError`). It is a rendering
|
|
209
|
+
and shows such bytes with U+FFFD replacement characters now; the
|
|
210
|
+
accessors `body_str()` / `body_bytes()` raise as before, which is
|
|
211
|
+
documented.
|
|
212
|
+
- A custom redaction was lost on the way into a request or response:
|
|
213
|
+
`Headers.copy()` and the constructors rebuilt a plain `Headers`, so a
|
|
214
|
+
subclass or an instance with more `secret_names` printed its secrets
|
|
215
|
+
in `repr()`.
|
|
216
|
+
- The asynchronous file operations could be left behind by a shutdown:
|
|
217
|
+
cancelling all tasks of the loop (`asyncio.run()` on its way out, a
|
|
218
|
+
signal handler) also cancelled the task the worker thread was wrapped
|
|
219
|
+
in, and `asave_body()` closed its file while a write was still
|
|
220
|
+
running. The call is a plain future now.
|
|
221
|
+
- A `SpooledBody` whose rollover to the temporary file failed midway (a
|
|
222
|
+
full disk) kept answering with a part of the data — `content_length()`
|
|
223
|
+
said one thing, `as_bytes()` returned another — and the next write
|
|
224
|
+
raised an `AttributeError`. The body is closed now and the error
|
|
225
|
+
passes through.
|
|
226
|
+
- `Headers() == {"a": None}` (and other mappings that cannot be headers)
|
|
227
|
+
raised instead of being unequal.
|
|
228
|
+
- Reading a named pipe or a non-seekable file object with
|
|
229
|
+
`FileBody.achunks()` on asyncio started a thread per chunk; the daemon
|
|
230
|
+
threads are reused now.
|
|
231
|
+
- `Request.copy()` dropped a `secret_params` set on the instance, so the
|
|
232
|
+
copy made for a retry or a redirect printed in `repr()` what the
|
|
233
|
+
original redacted.
|
|
234
|
+
- `repr(request)` printed a token in the fragment of the URL
|
|
235
|
+
(`https://app.example/cb#access_token=…`) although its name is among
|
|
236
|
+
the `secret_params`.
|
|
237
|
+
- `as_str(include_body=True)` still raised for some charsets in the
|
|
238
|
+
`Content-Type`: `undefined` and `idna` (a `UnicodeError`), a name with
|
|
239
|
+
a NUL (`ValueError`). Every charset Python cannot decode with is read
|
|
240
|
+
as utf-8 now.
|
|
241
|
+
- The charset was read from inside a quoted parameter value:
|
|
242
|
+
`multipart/form-data; boundary="a;charset=latin-1"` made `latin-1` the
|
|
243
|
+
charset of the body. The parameters are split like `get_values()`
|
|
244
|
+
splits elements, outside of quoted strings only.
|
|
245
|
+
- A blocking iterable read with `IterableBody(..., threaded=True)` and a
|
|
246
|
+
non-seekable `FileBody` did not see the context variables of the task
|
|
247
|
+
reading them on asyncio, and a variable set inside such a call was
|
|
248
|
+
still set for the next, unrelated call served by the same thread. The
|
|
249
|
+
call runs in a copy of the caller's context, as in the loop's thread
|
|
250
|
+
pool.
|
|
251
|
+
- On trio, a read that was timed out while it was stuck (a silent pipe,
|
|
252
|
+
a blocking iterable) kept its place in trio's thread limiter until it
|
|
253
|
+
returned — forty of them, and no `trio.to_thread.run_sync()` in the
|
|
254
|
+
process got a thread anymore, this library's cleanup included. These
|
|
255
|
+
calls no longer count against trio's limiter, as they do not use the
|
|
256
|
+
loop's thread pool on asyncio.
|
|
257
|
+
- A stream could pass for complete after it had been cut: closing an
|
|
258
|
+
`IterableBody` / `AsyncIterableBody` with a callback while another
|
|
259
|
+
thread or task was waiting inside its generator ran the callback, and
|
|
260
|
+
when the generator — its connection gone — then returned instead of
|
|
261
|
+
raising, the reader got the chunks so far as the whole body. That read
|
|
262
|
+
raises the `RuntimeError` of a body closed midway now. A generator
|
|
263
|
+
closing its own body on its way out is still a regular end.
|
|
264
|
+
- Giving up a read of an `AsyncIterableBody` over a re-iterable source
|
|
265
|
+
(an object whose `__aiter__` is an async generator function) left the
|
|
266
|
+
generator of that read open — and what its `finally` releases held —
|
|
267
|
+
until the loop got around to it; the synchronous `close()` reported
|
|
268
|
+
nothing to release meanwhile. The generator is closed with the read,
|
|
269
|
+
and likewise for `IterableBody.achunks()`.
|
|
270
|
+
- The end of a cancelled read with `threaded=True` could raise
|
|
271
|
+
`ValueError: generator already executing` in place of the
|
|
272
|
+
cancellation, when the thread left behind entered the generator just
|
|
273
|
+
as the body closed it.
|
|
274
|
+
- A `SpooledBody` handed out the remains of a write that had failed
|
|
275
|
+
midway (a full disk) as part of the body: `content_length()` said 4
|
|
276
|
+
and `as_bytes()` returned 7 bytes. Every reader ends where the last
|
|
277
|
+
complete write ended.
|
|
278
|
+
- Two `abody_file()` calls on responses sharing a path-based `FileBody`
|
|
279
|
+
could lose track of one of the files they opened, which `close()` then
|
|
280
|
+
left open.
|
|
281
|
+
- `Headers`: `items()`, `dict(headers)`, `update()` and equality took
|
|
282
|
+
time quadratic in the number of lines, every lookup folding every
|
|
283
|
+
stored name. The fields are indexed once per change.
|
|
284
|
+
- `IterableBody(..., threaded=True)` on trio looked up the name of
|
|
285
|
+
trio's keyword with `inspect.signature()` for every chunk.
|
|
286
|
+
|
|
287
|
+
Earlier releases of action0-req accept action0-url 0.2.0 as well, and
|
|
288
|
+
these show up with it:
|
|
289
|
+
|
|
290
|
+
- `Request.as_str()` wrote a request target that differed from the URL
|
|
291
|
+
of the request, because it was rebuilt from the decoded parts: an
|
|
292
|
+
escaped `/` became a real one (`/a%2Fb` → `/a/b`), `%7E` became `~`,
|
|
293
|
+
an escape that is not valid UTF-8 became `%EF%BF%BD`, and for schemes
|
|
294
|
+
other than `http`, `https`, `ws` and `wss` a `+` in the query was
|
|
295
|
+
written as `%2B`. The target is now the URL's own spelling of path,
|
|
296
|
+
path params and query, character for character.
|
|
297
|
+
- `Request(url, query="a+b")` read the `+` of a query string as a space
|
|
298
|
+
for every scheme; it is read like the `Url` constructor reads it now
|
|
299
|
+
(as a space only for `http`, `https`, `ws`, `wss` and URLs without a
|
|
300
|
+
scheme).
|
|
301
|
+
|
|
302
|
+
Independent of the action0-url version:
|
|
303
|
+
|
|
304
|
+
- A path with an empty first segment (`https://example.com//a`) got a
|
|
305
|
+
wrong target in `Request.as_str()`: `////a` with action0-url 0.1.0,
|
|
306
|
+
`/.//a` with 0.2.0. It is `//a` now.
|
|
307
|
+
- The `Host` header derived by `Request.as_str()` has the hostname as it
|
|
308
|
+
is written in the URL string: a non-ASCII hostname is IDNA-encoded
|
|
309
|
+
(`Host: xn--bcher-kva.example`, was `bücher.example`). With action0-url
|
|
310
|
+
0.2.0 an IPv6 address also keeps its brackets (`Host: [::1]:8080`, was
|
|
311
|
+
`::1:8080`).
|
|
312
|
+
|
|
313
|
+
## 0.2.0 — 2026-11-26
|
|
314
|
+
|
|
315
|
+
### Added
|
|
316
|
+
|
|
317
|
+
- `SpooledBody`: a body producer that is written first and read
|
|
318
|
+
afterwards. It keeps the data in memory up to `max_memory` bytes and
|
|
319
|
+
moves it to an anonymous temporary file beyond that. It is re-readable,
|
|
320
|
+
also by several consumers at once, offers read-only, seekable file
|
|
321
|
+
views via `file()`, and is removed deterministically by `close()` or a
|
|
322
|
+
`with` block. `awrite()`, `achunks()` and `aclose()` do their file I/O
|
|
323
|
+
in a worker thread.
|
|
324
|
+
- `Response.body_file()`: the response body as a seekable binary file
|
|
325
|
+
object, whatever form the body has. A streamed body is spooled, and
|
|
326
|
+
the stream closed; a `FileBody` hands out its file without a copy
|
|
327
|
+
(`FileBody.close()` closes a file opened for that).
|
|
328
|
+
- `Response.save_body()` and `Response.asave_body()`, plus the functions
|
|
329
|
+
`save_body()` and `asave_body()`: copy a body into a path or an open
|
|
330
|
+
file object chunk by chunk, with `append=True` for resumed downloads.
|
|
331
|
+
A path is opened only once the body has delivered its first chunk, so
|
|
332
|
+
a body that cannot be read leaves an existing file untouched. A write
|
|
333
|
+
that fails closes the stream.
|
|
334
|
+
- `Response.close()` and `Response.aclose()`; a response is now a sync
|
|
335
|
+
and async context manager. They release what the body holds and do
|
|
336
|
+
nothing for in-memory bodies. When a `with` block is left by an
|
|
337
|
+
exception, a failure to close is attached to that exception as a note
|
|
338
|
+
instead of replacing it.
|
|
339
|
+
- `IterableBody(..., close=...)` and `AsyncIterableBody(..., aclose=...)`:
|
|
340
|
+
a callback releasing the resource behind the stream. It runs exactly
|
|
341
|
+
once: after the body has been consumed, when a consumer stops early,
|
|
342
|
+
or on `close()` / `aclose()`. Both classes are context managers.
|
|
343
|
+
Closing also closes a generator behind the body, so one that was read
|
|
344
|
+
in part runs its `finally` blocks right away.
|
|
345
|
+
`AsyncIterableBody.close()` is the synchronous counterpart for a body
|
|
346
|
+
with nothing left to release; it raises while the callback is pending.
|
|
347
|
+
- trio support for asynchronous file I/O: `FileBody.achunks()` and the
|
|
348
|
+
new asynchronous file operations use trio's thread pool when running
|
|
349
|
+
below trio. Before, `FileBody.achunks()` worked on asyncio only.
|
|
350
|
+
Cleanup — closing a file, writing out what has arrived — also runs
|
|
351
|
+
when the task has been cancelled.
|
|
352
|
+
|
|
353
|
+
### Fixed
|
|
354
|
+
|
|
355
|
+
- `FileBody.achunks()` no longer leaves the file it opened unclosed when
|
|
356
|
+
the consuming task is cancelled: the close also runs when the task is
|
|
357
|
+
cancelled repeatedly, as anyio does on a timeout.
|
|
358
|
+
- `FileBody.achunks()` on asyncio: a cancelled read of a regular file or
|
|
359
|
+
a seekable file object is finished before the cancellation is passed
|
|
360
|
+
on, so it no longer moves the file position under the next reader. A
|
|
361
|
+
source that may block for good (a named pipe, a device, a non-seekable
|
|
362
|
+
file object) is still left behind at once — now in a daemon thread of
|
|
363
|
+
its own, which neither occupies the loop's thread pool nor delays its
|
|
364
|
+
shutdown, and which closes the file it opened.
|
|
365
|
+
|
|
366
|
+
## 0.1.1 — 2026-08-08
|
|
367
|
+
|
|
368
|
+
### Changed
|
|
369
|
+
|
|
370
|
+
- Installation instructions: the package is published on PyPI.
|
|
371
|
+
|
|
372
|
+
## 0.1.0 — 2026-08-08
|
|
373
|
+
|
|
374
|
+
First release: the `Header`, `Status` and `Method` constants, `Headers`,
|
|
375
|
+
`Request`, `Response` and the `BodyProducer` protocol with `BytesBody`,
|
|
376
|
+
`FileBody`, `IterableBody` and `AsyncIterableBody`.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Project
|
|
6
|
+
|
|
7
|
+
`action0-req` is a Python library for representing, creating and manipulating HTTP requests and responses. It ships the `action0.req` package (`action0` is a PEP 420 namespace package) from a `src/` layout, is built with hatchling, and uses `uv` for environment/dependency management. Its only runtime dependency is `action0-url` (the URL representation, `>=0.2.1,<0.3` — 0.2.1 for `Url.request_target`/`Url.raw_authority`; capped below the next minor, since a 0.x minor may change behaviour: `Url` keeps its parts percent-encoded and round-trips a URL string as written), pulled from PyPI.
|
|
8
|
+
|
|
9
|
+
## Rules
|
|
10
|
+
|
|
11
|
+
- **Never commit without asking.** Also never push, tag, or publish on your own.
|
|
12
|
+
- **Branches + PRs.** All changes go through feature branches and GitHub pull requests that Simon reviews and merges — never commit to `main` directly. (Only the initial implementation was built directly on `main`; that phase is over.)
|
|
13
|
+
- **Discuss first.** Always present the plan and the intended edits and get agreement before changing files.
|
|
14
|
+
- Every code change comes with: tests, docstrings, inline comments where the code isn't self-explanatory, and updated usage examples in `README.md` and the Sphinx docs (`docs/usage.md`).
|
|
15
|
+
- Before considering work done, run ruff, mypy, and pytest (commands below) and fix what they report.
|
|
16
|
+
- Supported Python versions: 3.11 up to the latest release. Don't use syntax or stdlib features introduced after 3.11, and don't rely on behavior removed in newer versions.
|
|
17
|
+
|
|
18
|
+
## Commands
|
|
19
|
+
|
|
20
|
+
`uv run` syncs the environment automatically (the dev dependency group is installed by default), so no separate install step is needed.
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
uv run pytest # all tests
|
|
24
|
+
uv run pytest tests/action0/req/test_init.py # one file
|
|
25
|
+
uv run pytest tests/action0/req/test_init.py::PackageTestCase::test_version # one test
|
|
26
|
+
|
|
27
|
+
uv run ruff check # lint (add --fix to autofix)
|
|
28
|
+
uv run ruff format # format
|
|
29
|
+
uv run mypy # type-check (strict; files are configured in pyproject.toml)
|
|
30
|
+
uv run pyright # type-check
|
|
31
|
+
uv run ty check # type-check
|
|
32
|
+
|
|
33
|
+
uv run --group docs sphinx-build -W --keep-going -b html docs docs/_build/html # build docs
|
|
34
|
+
|
|
35
|
+
uv build # build sdist + wheel into dist/
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
`pytest` also runs the `>>>` examples in the docstrings as doctests (`--doctest-modules` over `src/`), so docstring examples must produce their shown output exactly.
|
|
39
|
+
|
|
40
|
+
## Architecture
|
|
41
|
+
|
|
42
|
+
The modules under `src/action0/req/`:
|
|
43
|
+
|
|
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.
|
|
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`).
|
|
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.
|
|
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.
|
|
49
|
+
- `response.py` — `Response`: `status` (any int; `Status` members welcome; a property raising `TypeError` for anything else — a `bool` included —, stored in `__dict__["status"]` so old pickles load; rendered with `int()`, so a foreign int enum shows its number), `headers` (a converting property as on `Request`), `body`, `reason` (server-sent phrase; `None` = not known: the `phrase` property falls back to the `Status` registry, `""` for unknown codes; `""` = the server sent none), `http_version`, an optional `request` back-reference (metadata: shared, not copied, excluded from `__eq__`) and a `meta` dict like `Request`'s. Category properties (`is_success`, …) computed from the numeric range so unregistered codes work. Same body accessors as `Request` (sync and async), plus the response-only `body_file(max_memory=, dir=)` and its asynchronous twin `abody_file()` (reads via `achunks()`, spools with `awrite()`, awaits the replaced producer's `aclose()`; the `FileBody` lookup runs in a worker thread) (seekable file view; a streamed body is spooled and the `SpooledBody` REPLACES `body` so the response stays readable and closable; the replaced producer is closed. A producer with only `aclose()` is replaced by the private `_SpooledStream`, which carries that `aclose()` along. A `FileBody` is not copied and not replaced where it can hand out a seekable file itself (see `_file_view()`); otherwise it is spooled. A `SpooledBody` hands out a new read-only view per call), `save_body()`/`asave_body()` and `close()`/`aclose()` + sync/async context manager (release the body's connection or temp file; no-ops for in-memory bodies; `close()` raises `RuntimeError` for a body that only an awaited `aclose()` can release — the body's own `close()` raises it, or it has none; `__exit__`/`__aexit__` with an exception in flight attach any `Exception` from closing to it as a note instead of replacing it). Picklable with an in-memory body (pinned by a test — out-of-process caches rely on it). `copy(**overrides)` (same class; takes the rest of the instance dict along like `Request.copy()`), `as_str(include_body, separator)` with status line — the SP behind the status code stays also without a phrase (`"HTTP/1.1 599 "`, RFC 9112); an HTTP version that is empty or contains whitespace is a `ValueError` —, `from_str(text)` as its inverse (the phrase becomes `reason`, a missing one `""` — never `None`, which would make `as_str()` invent the registry phrase; documented normalizations: the SP behind the code is always written, the code as a number), redacting-by-omission `repr()` (`Response(404 Not Found)`).
|
|
50
|
+
|
|
51
|
+
Conventions:
|
|
52
|
+
|
|
53
|
+
- The version is single-sourced as `__version__` in `src/action0/req/__init__.py`; hatch extracts it with the regex in `[tool.hatch.version]`. Bump it only there.
|
|
54
|
+
- Releases: pushing a `vX.Y.Z` tag triggers `.github/workflows/release.yml`, which checks that the tag is on `main`, re-runs all checks, verifies the tag matches `__version__` and that `CHANGELOG.md` has a `## X.Y.Z — YYYY-MM-DD` section, builds, and publishes to PyPI via trusted publishing (environment `pypi`). Never bump the version, tag, or publish on your own — releasing is the user's call.
|
|
55
|
+
- Tests mirror the `src/` layout under `tests/action0/req/` and are `unittest.TestCase` classes, executed via pytest. `tests/test_docs.py` runs every Python block of `README.md` and `docs/usage.md` and compares what it prints with the block's `#` comments.
|
|
56
|
+
- Ruff enforces one import per line (isort `force-single-line`), line length 99, `action0` as first-party.
|
|
57
|
+
- Docs live in `docs/` (Sphinx + Furo, MyST Markdown pages, autodoc for the API reference). Docstrings are Sphinx-reST (`:param:`, `:py:meth:` roles). CI builds them with `-W` on every run and deploys to GitHub Pages on pushes to `main`; `nitpicky` is on, so a cross-reference without a target fails the build. Guide examples in `docs/usage.md` show exact outputs in `#` comments — `tests/test_docs.py` holds them to it.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: action0-req
|
|
3
|
-
Version: 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
|
|
26
|
+
Requires-Dist: action0-url<0.3,>=0.2.2
|
|
27
27
|
Description-Content-Type: text/markdown
|
|
28
28
|
|
|
29
29
|
# Action0-Req
|
|
@@ -57,8 +57,9 @@ pip install action0-req # or uv add action0-req
|
|
|
57
57
|
## Usage
|
|
58
58
|
|
|
59
59
|
`Header`, `Status` and `Method` are `StrEnum`/`IntEnum` constants for the
|
|
60
|
-
IANA-registered header field names
|
|
61
|
-
every member *is* its
|
|
60
|
+
IANA-registered header field names and status codes and for the request
|
|
61
|
+
methods of RFC 9110 (plus `PATCH` and `QUERY`) — every member *is* its
|
|
62
|
+
string or integer value:
|
|
62
63
|
|
|
63
64
|
```python
|
|
64
65
|
from action0.req import Header, Method, Status
|
|
@@ -91,9 +92,16 @@ print(headers.as_str(separator="\n")) # "\r\n" by default
|
|
|
91
92
|
print(Headers({"Authorization": "Bearer tok"})) # Headers(Authorization: ***)
|
|
92
93
|
```
|
|
93
94
|
|
|
95
|
+
A name or value containing a line break is refused with a `ValueError`,
|
|
96
|
+
so a value from user input cannot smuggle in a header of its own — and
|
|
97
|
+
so is a name that is empty or contains whitespace or a colon. Names are
|
|
98
|
+
matched by their ASCII letters only, as on the wire: a lookalike such as
|
|
99
|
+
`Hoſt` is not the `Host` header.
|
|
100
|
+
|
|
94
101
|
`Request` combines a method, a `Url` (from action0-url), `Headers`, a
|
|
95
|
-
`meta` dict for application metadata (never on the wire) and a body
|
|
96
|
-
|
|
102
|
+
`meta` dict for application metadata (never on the wire) and a body
|
|
103
|
+
(`bytes`, `str` or a streaming `BodyProducer` — retrievable in any of
|
|
104
|
+
the three forms, synchronously or with `abody_bytes()` / `abody_str()`):
|
|
97
105
|
|
|
98
106
|
```python
|
|
99
107
|
from action0.req import Request
|
|
@@ -108,8 +116,33 @@ print(req.as_str(separator="\n")) # "\r\n" by default
|
|
|
108
116
|
post = req.copy(method="POST", body='{"a": 1}')
|
|
109
117
|
print(post.body_bytes()) # b'{"a": 1}'
|
|
110
118
|
print(post) # Request(POST https://api.example.com/items?page=2)
|
|
119
|
+
|
|
120
|
+
# the URL is kept as it is written, up to the request line
|
|
121
|
+
signed = Request("https://api.example.com/a%2Fb?sig=x%2By&flag")
|
|
122
|
+
print(signed.as_str(separator="\n"))
|
|
123
|
+
# GET /a%2Fb?sig=x%2By&flag HTTP/1.1
|
|
124
|
+
# Host: api.example.com
|
|
125
|
+
print(signed) # repr() redacts secret query parameters and the password
|
|
126
|
+
# Request(GET https://api.example.com/a%2Fb?sig=***&flag)
|
|
127
|
+
|
|
128
|
+
# the target forms a URL cannot express are set explicitly
|
|
129
|
+
print(Request("https://example.com", "OPTIONS", target="*").as_str(separator="\n"))
|
|
130
|
+
# OPTIONS * HTTP/1.1
|
|
131
|
+
# Host: example.com
|
|
132
|
+
|
|
133
|
+
# and from_str() parses what as_str() renders
|
|
134
|
+
parsed = Request.from_str("GET /items?page=2 HTTP/1.1\nHost: api.example.com", scheme="https")
|
|
135
|
+
print(parsed.url) # https://api.example.com/items?page=2
|
|
136
|
+
|
|
137
|
+
# a string or a mapping assigned to url/headers is converted
|
|
138
|
+
parsed.headers = {"accept": "application/json"}
|
|
139
|
+
print(parsed.headers["Accept"]) # application/json
|
|
111
140
|
```
|
|
112
141
|
|
|
142
|
+
A method, target or HTTP version that would not stay one word of the
|
|
143
|
+
request line, and a `Host` header that is more than a host and a port,
|
|
144
|
+
are refused with a `ValueError`.
|
|
145
|
+
|
|
113
146
|
`Response` mirrors it for the server side — status (with reason phrase
|
|
114
147
|
fallback and category properties), headers, body:
|
|
115
148
|
|
|
@@ -121,11 +154,14 @@ print(resp.phrase, resp.is_client_error) # Not Found True
|
|
|
121
154
|
print(resp.as_str(separator="\n")) # "\r\n" by default
|
|
122
155
|
# HTTP/1.1 404 Not Found
|
|
123
156
|
# Content-Type: text/plain
|
|
157
|
+
print(Response.from_str("HTTP/1.1 204 No Content\nETag: abc").headers["ETag"]) # abc
|
|
124
158
|
```
|
|
125
159
|
|
|
126
160
|
A response body can also be read as a seekable file object and copied
|
|
127
161
|
into a file, and a response releases what its body holds (a connection,
|
|
128
|
-
a temporary file) when closed
|
|
162
|
+
a temporary file) when closed. A streamed body can be read once — a
|
|
163
|
+
second read raises instead of coming back empty —, and `body_file()`
|
|
164
|
+
(`abody_file()` in asynchronous code) is what keeps it readable:
|
|
129
165
|
|
|
130
166
|
```python
|
|
131
167
|
import gzip
|
|
@@ -138,6 +174,22 @@ with Response(200, body=IterableBody([compressed[:8], compressed[8:]])) as resp:
|
|
|
138
174
|
print(gzip.GzipFile(fileobj=resp.body_file()).read()) # b'a large report'
|
|
139
175
|
written = resp.save_body("report.gz") # a path or an open binary file
|
|
140
176
|
print(written == len(compressed)) # True
|
|
177
|
+
print(resp.body_bytes() == compressed) # True
|
|
178
|
+
```
|
|
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
|
+
)
|
|
141
193
|
```
|
|
142
194
|
|
|
143
195
|
## Development
|
|
@@ -152,7 +204,7 @@ uv run ruff format # format
|
|
|
152
204
|
uv run mypy # type-check (also: uv run pyright, uv run ty check)
|
|
153
205
|
|
|
154
206
|
# build the docs (Sphinx; deployed to GitHub Pages on push to main)
|
|
155
|
-
uv run --group docs sphinx-build -W docs docs/_build/html
|
|
207
|
+
uv run --group docs sphinx-build -W --keep-going -b html docs docs/_build/html
|
|
156
208
|
```
|
|
157
209
|
|
|
158
210
|
### Releasing
|