action0-req 0.1.0__py3-none-any.whl
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/__init__.py +27 -0
- action0/req/body.py +396 -0
- action0/req/headers.py +705 -0
- action0/req/py.typed +0 -0
- action0/req/request.py +261 -0
- action0/req/response.py +248 -0
- action0/req/status.py +152 -0
- action0_req-0.1.0.dist-info/METADATA +166 -0
- action0_req-0.1.0.dist-info/RECORD +11 -0
- action0_req-0.1.0.dist-info/WHEEL +4 -0
- action0_req-0.1.0.dist-info/licenses/LICENSE +21 -0
action0/req/py.typed
ADDED
|
File without changes
|
action0/req/request.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""The HTTP request representation (:py:class:`Request`) and the method constants."""
|
|
2
|
+
|
|
3
|
+
from enum import StrEnum
|
|
4
|
+
from typing import Any
|
|
5
|
+
from typing import Mapping
|
|
6
|
+
from typing import Union
|
|
7
|
+
|
|
8
|
+
from action0.url import Params
|
|
9
|
+
from action0.url import Url
|
|
10
|
+
from action0.url.params import ParamTypes
|
|
11
|
+
|
|
12
|
+
from .body import BodyProducer
|
|
13
|
+
from .body import BodyTypes
|
|
14
|
+
from .body import _body_bytes
|
|
15
|
+
from .body import _body_producer
|
|
16
|
+
from .body import _body_str
|
|
17
|
+
from .body import _charset
|
|
18
|
+
from .body import _rendered_body
|
|
19
|
+
from .headers import Header
|
|
20
|
+
from .headers import Headers
|
|
21
|
+
from .headers import HeaderTypes
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Method(StrEnum):
|
|
25
|
+
"""
|
|
26
|
+
The HTTP request methods ("verbs") as string constants.
|
|
27
|
+
|
|
28
|
+
The members are the methods defined by :rfc:`9110`, plus ``PATCH``
|
|
29
|
+
(:rfc:`5789`) and ``QUERY`` (:rfc:`10008`). Being a
|
|
30
|
+
:py:class:`enum.StrEnum`, every member *is* the method string:
|
|
31
|
+
|
|
32
|
+
>>> from action0.req import Method
|
|
33
|
+
>>> print(Method.GET)
|
|
34
|
+
GET
|
|
35
|
+
>>> Method.GET == "GET"
|
|
36
|
+
True
|
|
37
|
+
>>> Method("POST") is Method.POST
|
|
38
|
+
True
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
CONNECT = "CONNECT"
|
|
42
|
+
DELETE = "DELETE"
|
|
43
|
+
GET = "GET"
|
|
44
|
+
HEAD = "HEAD"
|
|
45
|
+
OPTIONS = "OPTIONS"
|
|
46
|
+
PATCH = "PATCH"
|
|
47
|
+
POST = "POST"
|
|
48
|
+
PUT = "PUT"
|
|
49
|
+
QUERY = "QUERY"
|
|
50
|
+
TRACE = "TRACE"
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Request:
|
|
54
|
+
r"""
|
|
55
|
+
Python representation of an HTTP request: method, URL, headers, body
|
|
56
|
+
and HTTP version — every part a plain mutable attribute
|
|
57
|
+
(:py:class:`~action0.url.base.Url` for the URL,
|
|
58
|
+
:py:class:`~action0.req.headers.Headers` for the headers).
|
|
59
|
+
|
|
60
|
+
Example::
|
|
61
|
+
|
|
62
|
+
>>> req = Request("https://api.example.com/items", query={"page": 2})
|
|
63
|
+
>>> req.method
|
|
64
|
+
'GET'
|
|
65
|
+
>>> req.url.as_str()
|
|
66
|
+
'https://api.example.com/items?page=2'
|
|
67
|
+
>>> req.headers["Accept"] = "application/json"
|
|
68
|
+
>>> print(req.as_str(separator="\n"))
|
|
69
|
+
GET /items?page=2 HTTP/1.1
|
|
70
|
+
Host: api.example.com
|
|
71
|
+
Accept: application/json
|
|
72
|
+
>>> req
|
|
73
|
+
Request(GET https://api.example.com/items?page=2)
|
|
74
|
+
|
|
75
|
+
The body can be set as ``bytes``, ``str`` or a streaming
|
|
76
|
+
:py:class:`~action0.req.body.BodyProducer` and retrieved in any of the
|
|
77
|
+
three forms via :py:meth:`body_bytes`, :py:meth:`body_str` and
|
|
78
|
+
:py:meth:`body_producer`, regardless of how it was set.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
def __init__(
|
|
82
|
+
self,
|
|
83
|
+
url: Union[str, Url, None] = None,
|
|
84
|
+
method: str = Method.GET,
|
|
85
|
+
*,
|
|
86
|
+
query: Union[ParamTypes, None] = None,
|
|
87
|
+
headers: Union[HeaderTypes, None] = None,
|
|
88
|
+
body: Union[BodyTypes, None] = None,
|
|
89
|
+
http_version: str = "HTTP/1.1",
|
|
90
|
+
meta: Union[Mapping[str, Any], None] = None,
|
|
91
|
+
) -> None:
|
|
92
|
+
"""
|
|
93
|
+
:param url: the URL to request, as a string or an existing
|
|
94
|
+
:py:class:`~action0.url.base.Url` (which is copied, so
|
|
95
|
+
the request owns its URL); ``None`` starts from an
|
|
96
|
+
empty URL to be filled in via ``request.url``
|
|
97
|
+
:param method: the HTTP method, e.g. a :py:class:`Method` member or
|
|
98
|
+
any string (uppercased on the way in)
|
|
99
|
+
:param query: if given, replaces the query of the given URL — like
|
|
100
|
+
the ``query`` argument of the ``Url`` constructor
|
|
101
|
+
:param headers: the initial header lines, in any form accepted by
|
|
102
|
+
:py:class:`~action0.req.headers.Headers`
|
|
103
|
+
:param body: the request body as ``bytes``, ``str`` or a streaming
|
|
104
|
+
:py:class:`~action0.req.body.BodyProducer`
|
|
105
|
+
:param http_version: the protocol version rendered in the request
|
|
106
|
+
line
|
|
107
|
+
:param meta: initial application metadata riding along with the
|
|
108
|
+
request (see :py:attr:`meta`)
|
|
109
|
+
"""
|
|
110
|
+
if url is None:
|
|
111
|
+
self.url = Url()
|
|
112
|
+
elif isinstance(url, Url):
|
|
113
|
+
# copy on ingestion (like Headers/Params) so later changes to
|
|
114
|
+
# the caller's Url and to request.url are independent
|
|
115
|
+
self.url = url.copy()
|
|
116
|
+
else:
|
|
117
|
+
self.url = Url(url)
|
|
118
|
+
if query is not None:
|
|
119
|
+
self.url.query = Params(query)
|
|
120
|
+
|
|
121
|
+
self.method: str = method.upper()
|
|
122
|
+
self.headers = Headers(headers)
|
|
123
|
+
self.body: Union[BodyTypes, None] = body
|
|
124
|
+
self.http_version = http_version
|
|
125
|
+
self.meta: dict[str, Any] = dict(meta) if meta is not None else {}
|
|
126
|
+
"""Application metadata riding along with the request — correlation
|
|
127
|
+
ids, tracing context, per-request knobs for custom backends, ... —
|
|
128
|
+
never sent on the wire and not part of :py:meth:`__eq__`. The dict
|
|
129
|
+
is the request's own (the constructor copies the given mapping);
|
|
130
|
+
libraries should namespace their keys (e.g.
|
|
131
|
+
``"my-lib.correlation-id"``)."""
|
|
132
|
+
|
|
133
|
+
def body_bytes(self) -> Union[bytes, None]:
|
|
134
|
+
"""
|
|
135
|
+
The body as bytes, regardless of how it was set: bytes are
|
|
136
|
+
returned as-is, a str is encoded with the Content-Type charset
|
|
137
|
+
(default utf-8), a :py:class:`~action0.req.body.BodyProducer` is
|
|
138
|
+
read in full.
|
|
139
|
+
|
|
140
|
+
:return: the body bytes, ``None`` if there is no body
|
|
141
|
+
"""
|
|
142
|
+
return _body_bytes(self.body, _charset(self.headers))
|
|
143
|
+
|
|
144
|
+
def body_str(self) -> Union[str, None]:
|
|
145
|
+
"""
|
|
146
|
+
The body as text, regardless of how it was set: a str is returned
|
|
147
|
+
as-is, bytes are decoded with the Content-Type charset (default
|
|
148
|
+
utf-8), a :py:class:`~action0.req.body.BodyProducer` is read in
|
|
149
|
+
full and decoded.
|
|
150
|
+
|
|
151
|
+
:return: the body text, ``None`` if there is no body
|
|
152
|
+
"""
|
|
153
|
+
return _body_str(self.body, _charset(self.headers))
|
|
154
|
+
|
|
155
|
+
def body_producer(self) -> Union[BodyProducer, None]:
|
|
156
|
+
"""
|
|
157
|
+
The body as a streaming producer, regardless of how it was set: a
|
|
158
|
+
:py:class:`~action0.req.body.BodyProducer` is returned as-is,
|
|
159
|
+
bytes and str are wrapped in an in-memory
|
|
160
|
+
:py:class:`~action0.req.body.BytesBody` (str encoded with the
|
|
161
|
+
Content-Type charset first).
|
|
162
|
+
|
|
163
|
+
:return: the body producer, ``None`` if there is no body
|
|
164
|
+
"""
|
|
165
|
+
return _body_producer(self.body, _charset(self.headers))
|
|
166
|
+
|
|
167
|
+
def copy(self, **overrides: Any) -> "Request":
|
|
168
|
+
"""
|
|
169
|
+
An independent copy of this request (with its own ``Url``,
|
|
170
|
+
``Headers`` and ``meta`` dict), optionally with attributes
|
|
171
|
+
replaced. The body is carried over as-is — in particular a
|
|
172
|
+
:py:class:`~action0.req.body.BodyProducer` is shared, not copied;
|
|
173
|
+
the ``meta`` values are shared too (shallow copy).
|
|
174
|
+
|
|
175
|
+
Example::
|
|
176
|
+
|
|
177
|
+
>>> req = Request("https://api.example.com/items")
|
|
178
|
+
>>> req.copy(method="POST", body="{}")
|
|
179
|
+
Request(POST https://api.example.com/items)
|
|
180
|
+
|
|
181
|
+
:param overrides: any attribute accepted by the constructor
|
|
182
|
+
:return: a new Request, this instance is not modified
|
|
183
|
+
"""
|
|
184
|
+
kwargs: dict[str, Any] = {
|
|
185
|
+
"url": self.url,
|
|
186
|
+
"method": self.method,
|
|
187
|
+
"headers": self.headers,
|
|
188
|
+
"body": self.body,
|
|
189
|
+
"http_version": self.http_version,
|
|
190
|
+
"meta": self.meta,
|
|
191
|
+
}
|
|
192
|
+
kwargs.update(overrides)
|
|
193
|
+
return Request(**kwargs)
|
|
194
|
+
|
|
195
|
+
def as_str(self, include_body: bool = False, separator: str = "\r\n") -> str:
|
|
196
|
+
r"""
|
|
197
|
+
The wire representation: the request line with the origin-form
|
|
198
|
+
target (path and query), the header lines — with a ``Host`` header
|
|
199
|
+
derived from the URL if none is set — and optionally the body.
|
|
200
|
+
Secret header values are NOT redacted here, unlike in ``repr()``.
|
|
201
|
+
|
|
202
|
+
:param include_body: append a blank line and the body (as text,
|
|
203
|
+
via :py:meth:`body_str`); a
|
|
204
|
+
:py:class:`~action0.req.body.BodyProducer` is
|
|
205
|
+
not consumed — a placeholder is shown instead
|
|
206
|
+
:param separator: the string joining the lines (no trailing one)
|
|
207
|
+
:return: e.g. ``"GET /items?page=2 HTTP/1.1\r\nHost: api.example.com"``
|
|
208
|
+
"""
|
|
209
|
+
# origin-form target: path (with path params) and query, no authority
|
|
210
|
+
target = Url(
|
|
211
|
+
path=self.url.path or "/",
|
|
212
|
+
path_params=self.url.path_params,
|
|
213
|
+
query=self.url.query,
|
|
214
|
+
).as_str()
|
|
215
|
+
|
|
216
|
+
lines = [f"{self.method} {target} {self.http_version}"]
|
|
217
|
+
if Header.HOST not in self.headers and self.url.authority:
|
|
218
|
+
lines.append(f"Host: {self.url.authority}")
|
|
219
|
+
if self.headers:
|
|
220
|
+
lines.append(self.headers.as_str(separator))
|
|
221
|
+
rendered = separator.join(lines)
|
|
222
|
+
|
|
223
|
+
if include_body and self.body is not None:
|
|
224
|
+
body_text = _rendered_body(self.body, _charset(self.headers))
|
|
225
|
+
rendered = f"{rendered}{separator}{separator}{body_text}"
|
|
226
|
+
return rendered
|
|
227
|
+
|
|
228
|
+
def __eq__(self, other: object) -> bool:
|
|
229
|
+
"""
|
|
230
|
+
Requests are equal when their method, URL, headers, body and HTTP
|
|
231
|
+
version are equal, each with the part's own equality semantics
|
|
232
|
+
(e.g. header name casing doesn't matter). The body is compared as
|
|
233
|
+
set: ``b"x"`` and ``"x"`` are different bodies. The
|
|
234
|
+
:py:attr:`meta` dict is metadata and not compared.
|
|
235
|
+
|
|
236
|
+
:param other: the Request to compare with
|
|
237
|
+
:return: whether the requests are equal
|
|
238
|
+
"""
|
|
239
|
+
if isinstance(other, Request):
|
|
240
|
+
return (
|
|
241
|
+
self.method == other.method
|
|
242
|
+
and self.http_version == other.http_version
|
|
243
|
+
and self.url == other.url
|
|
244
|
+
and self.headers == other.headers
|
|
245
|
+
and self.body == other.body
|
|
246
|
+
)
|
|
247
|
+
return NotImplemented
|
|
248
|
+
|
|
249
|
+
def __repr__(self) -> str:
|
|
250
|
+
"""
|
|
251
|
+
:return: the method and the URL, with the password redacted like
|
|
252
|
+
``repr(Url)`` does; headers and body are left out, so no
|
|
253
|
+
secret header values can leak. ``str()`` falls back to
|
|
254
|
+
this representation — the wire rendering is only
|
|
255
|
+
available explicitly via :py:meth:`as_str`.
|
|
256
|
+
"""
|
|
257
|
+
# reuse Url.__repr__ for its password redaction: "Url(...)" -> "..."
|
|
258
|
+
url_repr = repr(self.url)
|
|
259
|
+
redacted_url = url_repr[url_repr.find("(") + 1 : -1]
|
|
260
|
+
inner = " ".join(part for part in (self.method, redacted_url) if part)
|
|
261
|
+
return f"{self.__class__.__name__}({inner})"
|
action0/req/response.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
"""The HTTP response representation (:py:class:`Response`)."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
from typing import Mapping
|
|
5
|
+
from typing import Union
|
|
6
|
+
|
|
7
|
+
from .body import BodyProducer
|
|
8
|
+
from .body import BodyTypes
|
|
9
|
+
from .body import _body_bytes
|
|
10
|
+
from .body import _body_producer
|
|
11
|
+
from .body import _body_str
|
|
12
|
+
from .body import _charset
|
|
13
|
+
from .body import _rendered_body
|
|
14
|
+
from .headers import Headers
|
|
15
|
+
from .headers import HeaderTypes
|
|
16
|
+
from .request import Request
|
|
17
|
+
from .status import Status
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Response:
|
|
21
|
+
r"""
|
|
22
|
+
Python representation of an HTTP response: status, headers, body and
|
|
23
|
+
HTTP version — every part a plain mutable attribute (the headers a
|
|
24
|
+
:py:class:`~action0.req.headers.Headers`).
|
|
25
|
+
|
|
26
|
+
Example::
|
|
27
|
+
|
|
28
|
+
>>> resp = Response(404, headers={"Content-Type": "text/plain"}, body="not here")
|
|
29
|
+
>>> resp.status
|
|
30
|
+
404
|
|
31
|
+
>>> resp.phrase
|
|
32
|
+
'Not Found'
|
|
33
|
+
>>> resp.is_client_error
|
|
34
|
+
True
|
|
35
|
+
>>> print(resp.as_str(include_body=True, separator="\n"))
|
|
36
|
+
HTTP/1.1 404 Not Found
|
|
37
|
+
Content-Type: text/plain
|
|
38
|
+
<BLANKLINE>
|
|
39
|
+
not here
|
|
40
|
+
>>> resp
|
|
41
|
+
Response(404 Not Found)
|
|
42
|
+
|
|
43
|
+
The body works exactly like the request body: set as ``bytes``,
|
|
44
|
+
``str`` or a streaming :py:class:`~action0.req.body.BodyProducer`,
|
|
45
|
+
retrieved in any of the three forms via :py:meth:`body_bytes`,
|
|
46
|
+
:py:meth:`body_str` and :py:meth:`body_producer`.
|
|
47
|
+
"""
|
|
48
|
+
|
|
49
|
+
def __init__(
|
|
50
|
+
self,
|
|
51
|
+
status: int = Status.OK,
|
|
52
|
+
*,
|
|
53
|
+
headers: Union[HeaderTypes, None] = None,
|
|
54
|
+
body: Union[BodyTypes, None] = None,
|
|
55
|
+
reason: Union[str, None] = None,
|
|
56
|
+
http_version: str = "HTTP/1.1",
|
|
57
|
+
request: Union[Request, None] = None,
|
|
58
|
+
meta: Union[Mapping[str, Any], None] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""
|
|
61
|
+
:param status: the status code, a :py:class:`~action0.req.status.Status`
|
|
62
|
+
member or any int — unregistered codes are fine
|
|
63
|
+
:param headers: the initial header lines, in any form accepted by
|
|
64
|
+
:py:class:`~action0.req.headers.Headers`
|
|
65
|
+
:param body: the response body as ``bytes``, ``str`` or a streaming
|
|
66
|
+
:py:class:`~action0.req.body.BodyProducer`
|
|
67
|
+
:param reason: the reason phrase as sent by the server; ``None``
|
|
68
|
+
falls back to the registry phrase of the status code
|
|
69
|
+
(see :py:attr:`phrase`)
|
|
70
|
+
:param http_version: the protocol version rendered in the status
|
|
71
|
+
line
|
|
72
|
+
:param request: the request that produced this response — metadata:
|
|
73
|
+
shared, not copied, and not part of equality
|
|
74
|
+
:param meta: initial application metadata riding along with the
|
|
75
|
+
response (see :py:attr:`meta`)
|
|
76
|
+
"""
|
|
77
|
+
self.status: int = status
|
|
78
|
+
self.headers = Headers(headers)
|
|
79
|
+
self.body: Union[BodyTypes, None] = body
|
|
80
|
+
self.reason = reason
|
|
81
|
+
self.http_version = http_version
|
|
82
|
+
self.request = request
|
|
83
|
+
self.meta: dict[str, Any] = dict(meta) if meta is not None else {}
|
|
84
|
+
"""Application metadata riding along with the response — e.g. a
|
|
85
|
+
backend's native response object, cache markers, timings — never
|
|
86
|
+
sent on the wire and not part of :py:meth:`__eq__`. The dict is
|
|
87
|
+
the response's own (the constructor copies the given mapping);
|
|
88
|
+
libraries should namespace their keys."""
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def phrase(self) -> str:
|
|
92
|
+
"""
|
|
93
|
+
The reason phrase: the explicitly set :py:attr:`reason` if there is
|
|
94
|
+
one, otherwise the registry phrase of the status code, otherwise
|
|
95
|
+
(for unregistered codes) an empty string.
|
|
96
|
+
"""
|
|
97
|
+
if self.reason is not None:
|
|
98
|
+
return self.reason
|
|
99
|
+
try:
|
|
100
|
+
return Status(self.status).phrase
|
|
101
|
+
except ValueError:
|
|
102
|
+
return ""
|
|
103
|
+
|
|
104
|
+
@property
|
|
105
|
+
def is_informational(self) -> bool:
|
|
106
|
+
"""``True`` for 1xx statuses (works for any int status)."""
|
|
107
|
+
return 100 <= self.status <= 199
|
|
108
|
+
|
|
109
|
+
@property
|
|
110
|
+
def is_success(self) -> bool:
|
|
111
|
+
"""``True`` for 2xx statuses (works for any int status)."""
|
|
112
|
+
return 200 <= self.status <= 299
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def is_redirection(self) -> bool:
|
|
116
|
+
"""``True`` for 3xx statuses (works for any int status)."""
|
|
117
|
+
return 300 <= self.status <= 399
|
|
118
|
+
|
|
119
|
+
@property
|
|
120
|
+
def is_client_error(self) -> bool:
|
|
121
|
+
"""``True`` for 4xx statuses (works for any int status)."""
|
|
122
|
+
return 400 <= self.status <= 499
|
|
123
|
+
|
|
124
|
+
@property
|
|
125
|
+
def is_server_error(self) -> bool:
|
|
126
|
+
"""``True`` for 5xx statuses (works for any int status)."""
|
|
127
|
+
return 500 <= self.status <= 599
|
|
128
|
+
|
|
129
|
+
def body_bytes(self) -> Union[bytes, None]:
|
|
130
|
+
"""
|
|
131
|
+
The body as bytes, regardless of how it was set: bytes are
|
|
132
|
+
returned as-is, a str is encoded with the Content-Type charset
|
|
133
|
+
(default utf-8), a :py:class:`~action0.req.body.BodyProducer` is
|
|
134
|
+
read in full.
|
|
135
|
+
|
|
136
|
+
:return: the body bytes, ``None`` if there is no body
|
|
137
|
+
"""
|
|
138
|
+
return _body_bytes(self.body, _charset(self.headers))
|
|
139
|
+
|
|
140
|
+
def body_str(self) -> Union[str, None]:
|
|
141
|
+
"""
|
|
142
|
+
The body as text, regardless of how it was set: a str is returned
|
|
143
|
+
as-is, bytes are decoded with the Content-Type charset (default
|
|
144
|
+
utf-8), a :py:class:`~action0.req.body.BodyProducer` is read in
|
|
145
|
+
full and decoded.
|
|
146
|
+
|
|
147
|
+
:return: the body text, ``None`` if there is no body
|
|
148
|
+
"""
|
|
149
|
+
return _body_str(self.body, _charset(self.headers))
|
|
150
|
+
|
|
151
|
+
def body_producer(self) -> Union[BodyProducer, None]:
|
|
152
|
+
"""
|
|
153
|
+
The body as a streaming producer, regardless of how it was set: a
|
|
154
|
+
:py:class:`~action0.req.body.BodyProducer` is returned as-is,
|
|
155
|
+
bytes and str are wrapped in an in-memory
|
|
156
|
+
:py:class:`~action0.req.body.BytesBody` (str encoded with the
|
|
157
|
+
Content-Type charset first).
|
|
158
|
+
|
|
159
|
+
:return: the body producer, ``None`` if there is no body
|
|
160
|
+
"""
|
|
161
|
+
return _body_producer(self.body, _charset(self.headers))
|
|
162
|
+
|
|
163
|
+
def copy(self, **overrides: Any) -> "Response":
|
|
164
|
+
"""
|
|
165
|
+
An independent copy of this response (with its own ``Headers``
|
|
166
|
+
instance and ``meta`` dict), optionally with attributes replaced.
|
|
167
|
+
The body and the ``request`` reference are carried over as-is —
|
|
168
|
+
in particular a :py:class:`~action0.req.body.BodyProducer` is
|
|
169
|
+
shared, not copied; the ``meta`` values are shared too (shallow
|
|
170
|
+
copy).
|
|
171
|
+
|
|
172
|
+
Example::
|
|
173
|
+
|
|
174
|
+
>>> resp = Response(200, body="ok")
|
|
175
|
+
>>> resp.copy(status=404, reason="Nope")
|
|
176
|
+
Response(404 Nope)
|
|
177
|
+
|
|
178
|
+
:param overrides: any attribute accepted by the constructor
|
|
179
|
+
:return: a new Response, this instance is not modified
|
|
180
|
+
"""
|
|
181
|
+
kwargs: dict[str, Any] = {
|
|
182
|
+
"status": self.status,
|
|
183
|
+
"headers": self.headers,
|
|
184
|
+
"body": self.body,
|
|
185
|
+
"reason": self.reason,
|
|
186
|
+
"http_version": self.http_version,
|
|
187
|
+
"request": self.request,
|
|
188
|
+
"meta": self.meta,
|
|
189
|
+
}
|
|
190
|
+
kwargs.update(overrides)
|
|
191
|
+
return Response(**kwargs)
|
|
192
|
+
|
|
193
|
+
def as_str(self, include_body: bool = False, separator: str = "\r\n") -> str:
|
|
194
|
+
r"""
|
|
195
|
+
The wire representation: the status line (with the
|
|
196
|
+
:py:attr:`phrase`), the header lines and optionally the body.
|
|
197
|
+
Secret header values are NOT redacted here, unlike in ``repr()``.
|
|
198
|
+
|
|
199
|
+
:param include_body: append a blank line and the body (as text,
|
|
200
|
+
via :py:meth:`body_str`); a
|
|
201
|
+
:py:class:`~action0.req.body.BodyProducer` is
|
|
202
|
+
not consumed — a placeholder is shown instead
|
|
203
|
+
:param separator: the string joining the lines (no trailing one)
|
|
204
|
+
:return: e.g. ``"HTTP/1.1 404 Not Found\r\nContent-Length: 0"``
|
|
205
|
+
"""
|
|
206
|
+
# unregistered codes have no phrase — avoid a trailing space then
|
|
207
|
+
lines = [f"{self.http_version} {self.status} {self.phrase}".rstrip()]
|
|
208
|
+
if self.headers:
|
|
209
|
+
lines.append(self.headers.as_str(separator))
|
|
210
|
+
rendered = separator.join(lines)
|
|
211
|
+
|
|
212
|
+
if include_body and self.body is not None:
|
|
213
|
+
body_text = _rendered_body(self.body, _charset(self.headers))
|
|
214
|
+
rendered = f"{rendered}{separator}{separator}{body_text}"
|
|
215
|
+
return rendered
|
|
216
|
+
|
|
217
|
+
def __eq__(self, other: object) -> bool:
|
|
218
|
+
"""
|
|
219
|
+
Responses are equal when their status, reason, headers, body and
|
|
220
|
+
HTTP version are equal, each with the part's own equality
|
|
221
|
+
semantics (e.g. header name casing doesn't matter). The body is
|
|
222
|
+
compared as set: ``b"x"`` and ``"x"`` are different bodies. The
|
|
223
|
+
``request`` reference and the :py:attr:`meta` dict are metadata
|
|
224
|
+
and not compared.
|
|
225
|
+
|
|
226
|
+
:param other: the Response to compare with
|
|
227
|
+
:return: whether the responses are equal
|
|
228
|
+
"""
|
|
229
|
+
if isinstance(other, Response):
|
|
230
|
+
return (
|
|
231
|
+
self.status == other.status
|
|
232
|
+
and self.reason == other.reason
|
|
233
|
+
and self.http_version == other.http_version
|
|
234
|
+
and self.headers == other.headers
|
|
235
|
+
and self.body == other.body
|
|
236
|
+
)
|
|
237
|
+
return NotImplemented
|
|
238
|
+
|
|
239
|
+
def __repr__(self) -> str:
|
|
240
|
+
"""
|
|
241
|
+
:return: the status code and the :py:attr:`phrase`; headers and
|
|
242
|
+
body are left out, so no secret header values can leak.
|
|
243
|
+
``str()`` falls back to this representation — the wire
|
|
244
|
+
rendering is only available explicitly via
|
|
245
|
+
:py:meth:`as_str`.
|
|
246
|
+
"""
|
|
247
|
+
inner = f"{self.status} {self.phrase}".rstrip()
|
|
248
|
+
return f"{self.__class__.__name__}({inner})"
|
action0/req/status.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""Constants for the known HTTP status codes."""
|
|
2
|
+
|
|
3
|
+
from enum import IntEnum
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Status(IntEnum):
|
|
7
|
+
"""
|
|
8
|
+
The known HTTP status codes as integer constants.
|
|
9
|
+
|
|
10
|
+
The members are the codes from the `IANA HTTP status code registry
|
|
11
|
+
<https://www.iana.org/assignments/http-status-codes/>`_ as of
|
|
12
|
+
2026-08-07 with their registered reason phrases, plus the well-known
|
|
13
|
+
``418 I'm a Teapot`` from :rfc:`2324`. Being an
|
|
14
|
+
:py:class:`enum.IntEnum`, every member *is* its numeric code:
|
|
15
|
+
|
|
16
|
+
>>> from action0.req import Status
|
|
17
|
+
>>> print(Status.NOT_FOUND)
|
|
18
|
+
404
|
|
19
|
+
>>> Status.NOT_FOUND == 404
|
|
20
|
+
True
|
|
21
|
+
>>> Status.NOT_FOUND.phrase
|
|
22
|
+
'Not Found'
|
|
23
|
+
>>> Status(503).phrase
|
|
24
|
+
'Service Unavailable'
|
|
25
|
+
>>> Status.NOT_FOUND.is_client_error
|
|
26
|
+
True
|
|
27
|
+
|
|
28
|
+
:rfc:`9110` renamed two reason phrases; the pre-9110 names remain
|
|
29
|
+
available as aliases:
|
|
30
|
+
|
|
31
|
+
>>> Status.PAYLOAD_TOO_LARGE is Status.CONTENT_TOO_LARGE
|
|
32
|
+
True
|
|
33
|
+
>>> Status.UNPROCESSABLE_ENTITY is Status.UNPROCESSABLE_CONTENT
|
|
34
|
+
True
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
phrase: str
|
|
38
|
+
"""The registered reason phrase, e.g. ``"Not Found"`` for ``404``."""
|
|
39
|
+
|
|
40
|
+
# the default for "phrase" is never used (every member below passes one,
|
|
41
|
+
# and value lookups like Status(404) don't go through __new__ at all) —
|
|
42
|
+
# it only keeps type checkers happy about such lookup calls
|
|
43
|
+
def __new__(cls, value: int, phrase: str = "") -> "Status":
|
|
44
|
+
obj = int.__new__(cls, value)
|
|
45
|
+
obj._value_ = value
|
|
46
|
+
obj.phrase = phrase
|
|
47
|
+
return obj
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def is_informational(self) -> bool:
|
|
51
|
+
"""``True`` for the 1xx codes."""
|
|
52
|
+
return 100 <= self <= 199
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def is_success(self) -> bool:
|
|
56
|
+
"""``True`` for the 2xx codes."""
|
|
57
|
+
return 200 <= self <= 299
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def is_redirection(self) -> bool:
|
|
61
|
+
"""``True`` for the 3xx codes."""
|
|
62
|
+
return 300 <= self <= 399
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def is_client_error(self) -> bool:
|
|
66
|
+
"""``True`` for the 4xx codes."""
|
|
67
|
+
return 400 <= self <= 499
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def is_server_error(self) -> bool:
|
|
71
|
+
"""``True`` for the 5xx codes."""
|
|
72
|
+
return 500 <= self <= 599
|
|
73
|
+
|
|
74
|
+
# 1xx informational
|
|
75
|
+
CONTINUE = 100, "Continue"
|
|
76
|
+
SWITCHING_PROTOCOLS = 101, "Switching Protocols"
|
|
77
|
+
PROCESSING = 102, "Processing"
|
|
78
|
+
EARLY_HINTS = 103, "Early Hints"
|
|
79
|
+
|
|
80
|
+
# 2xx success
|
|
81
|
+
OK = 200, "OK"
|
|
82
|
+
CREATED = 201, "Created"
|
|
83
|
+
ACCEPTED = 202, "Accepted"
|
|
84
|
+
NON_AUTHORITATIVE_INFORMATION = 203, "Non-Authoritative Information"
|
|
85
|
+
NO_CONTENT = 204, "No Content"
|
|
86
|
+
RESET_CONTENT = 205, "Reset Content"
|
|
87
|
+
PARTIAL_CONTENT = 206, "Partial Content"
|
|
88
|
+
MULTI_STATUS = 207, "Multi-Status"
|
|
89
|
+
ALREADY_REPORTED = 208, "Already Reported"
|
|
90
|
+
IM_USED = 226, "IM Used"
|
|
91
|
+
|
|
92
|
+
# 3xx redirection
|
|
93
|
+
MULTIPLE_CHOICES = 300, "Multiple Choices"
|
|
94
|
+
MOVED_PERMANENTLY = 301, "Moved Permanently"
|
|
95
|
+
FOUND = 302, "Found"
|
|
96
|
+
SEE_OTHER = 303, "See Other"
|
|
97
|
+
NOT_MODIFIED = 304, "Not Modified"
|
|
98
|
+
# deprecated by RFC 9110 but still registered
|
|
99
|
+
USE_PROXY = 305, "Use Proxy"
|
|
100
|
+
TEMPORARY_REDIRECT = 307, "Temporary Redirect"
|
|
101
|
+
PERMANENT_REDIRECT = 308, "Permanent Redirect"
|
|
102
|
+
|
|
103
|
+
# 4xx client error
|
|
104
|
+
BAD_REQUEST = 400, "Bad Request"
|
|
105
|
+
UNAUTHORIZED = 401, "Unauthorized"
|
|
106
|
+
PAYMENT_REQUIRED = 402, "Payment Required"
|
|
107
|
+
FORBIDDEN = 403, "Forbidden"
|
|
108
|
+
NOT_FOUND = 404, "Not Found"
|
|
109
|
+
METHOD_NOT_ALLOWED = 405, "Method Not Allowed"
|
|
110
|
+
NOT_ACCEPTABLE = 406, "Not Acceptable"
|
|
111
|
+
PROXY_AUTHENTICATION_REQUIRED = 407, "Proxy Authentication Required"
|
|
112
|
+
REQUEST_TIMEOUT = 408, "Request Timeout"
|
|
113
|
+
CONFLICT = 409, "Conflict"
|
|
114
|
+
GONE = 410, "Gone"
|
|
115
|
+
LENGTH_REQUIRED = 411, "Length Required"
|
|
116
|
+
PRECONDITION_FAILED = 412, "Precondition Failed"
|
|
117
|
+
CONTENT_TOO_LARGE = 413, "Content Too Large"
|
|
118
|
+
URI_TOO_LONG = 414, "URI Too Long"
|
|
119
|
+
UNSUPPORTED_MEDIA_TYPE = 415, "Unsupported Media Type"
|
|
120
|
+
RANGE_NOT_SATISFIABLE = 416, "Range Not Satisfiable"
|
|
121
|
+
EXPECTATION_FAILED = 417, "Expectation Failed"
|
|
122
|
+
# 418 is reserved as "(Unused)" in the registry; kept as the well-known
|
|
123
|
+
# April-1st teapot (RFC 2324), like the stdlib's http.HTTPStatus
|
|
124
|
+
IM_A_TEAPOT = 418, "I'm a Teapot"
|
|
125
|
+
MISDIRECTED_REQUEST = 421, "Misdirected Request"
|
|
126
|
+
UNPROCESSABLE_CONTENT = 422, "Unprocessable Content"
|
|
127
|
+
LOCKED = 423, "Locked"
|
|
128
|
+
FAILED_DEPENDENCY = 424, "Failed Dependency"
|
|
129
|
+
TOO_EARLY = 425, "Too Early"
|
|
130
|
+
UPGRADE_REQUIRED = 426, "Upgrade Required"
|
|
131
|
+
PRECONDITION_REQUIRED = 428, "Precondition Required"
|
|
132
|
+
TOO_MANY_REQUESTS = 429, "Too Many Requests"
|
|
133
|
+
REQUEST_HEADER_FIELDS_TOO_LARGE = 431, "Request Header Fields Too Large"
|
|
134
|
+
UNAVAILABLE_FOR_LEGAL_REASONS = 451, "Unavailable For Legal Reasons"
|
|
135
|
+
|
|
136
|
+
# 5xx server error
|
|
137
|
+
INTERNAL_SERVER_ERROR = 500, "Internal Server Error"
|
|
138
|
+
NOT_IMPLEMENTED = 501, "Not Implemented"
|
|
139
|
+
BAD_GATEWAY = 502, "Bad Gateway"
|
|
140
|
+
SERVICE_UNAVAILABLE = 503, "Service Unavailable"
|
|
141
|
+
GATEWAY_TIMEOUT = 504, "Gateway Timeout"
|
|
142
|
+
HTTP_VERSION_NOT_SUPPORTED = 505, "HTTP Version Not Supported"
|
|
143
|
+
VARIANT_ALSO_NEGOTIATES = 506, "Variant Also Negotiates"
|
|
144
|
+
INSUFFICIENT_STORAGE = 507, "Insufficient Storage"
|
|
145
|
+
LOOP_DETECTED = 508, "Loop Detected"
|
|
146
|
+
# the registration was obsoleted in 2022, but the code is still around
|
|
147
|
+
NOT_EXTENDED = 510, "Not Extended"
|
|
148
|
+
NETWORK_AUTHENTICATION_REQUIRED = 511, "Network Authentication Required"
|
|
149
|
+
|
|
150
|
+
# pre-RFC-9110 reason phrase aliases
|
|
151
|
+
PAYLOAD_TOO_LARGE = CONTENT_TOO_LARGE
|
|
152
|
+
UNPROCESSABLE_ENTITY = UNPROCESSABLE_CONTENT
|