xtr-http-message-contracts 4.0.2__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.
@@ -0,0 +1,64 @@
1
+ """A response on its way out, as a server sends it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Protocol, Self, runtime_checkable
6
+
7
+ from .message_interface import MessageInterface
8
+
9
+ __all__ = ["ResponseInterface"]
10
+
11
+
12
+ @runtime_checkable
13
+ class ResponseInterface(MessageInterface, Protocol):
14
+ """An outgoing, server-side response.
15
+
16
+ On top of what every message carries — a protocol version, headers and a
17
+ body — a response carries a status code and the reason phrase that goes
18
+ with it.
19
+
20
+ Responses are immutable. Every ``with_*`` method keeps the instance it was
21
+ called on as it was and returns one carrying the change.
22
+ """
23
+
24
+ def get_status_code(self) -> int:
25
+ """Return the status code of the response.
26
+
27
+ Returns:
28
+ The three-digit code saying how the server got on with the
29
+ request.
30
+ """
31
+ ...
32
+
33
+ def with_status(self, code: int, reason_phrase: str = "") -> Self:
34
+ """Return an instance carrying ``code`` and, optionally, ``reason_phrase``.
35
+
36
+ Given no reason phrase, an implementation may fill in the one
37
+ recommended for that code — by the HTTP specification, or by the
38
+ registry of status codes kept alongside it.
39
+
40
+ Args:
41
+ code: The three-digit status code to set.
42
+ reason_phrase: The phrase to go with ``code``. Left out, the
43
+ implementation may choose the recommended one.
44
+
45
+ Returns:
46
+ A new instance; this one is left as it was.
47
+
48
+ Raises:
49
+ ValueError: When the status code is not a valid one.
50
+ """
51
+ ...
52
+
53
+ def get_reason_phrase(self) -> str:
54
+ """Return the reason phrase that goes with the status code.
55
+
56
+ A status line need not carry a reason phrase at all, so there may be
57
+ none to report; an implementation may answer with the phrase
58
+ recommended for the code instead — by the HTTP specification, or by
59
+ the registry of status codes kept alongside it.
60
+
61
+ Returns:
62
+ The reason phrase, or an empty string when there is none.
63
+ """
64
+ ...
@@ -0,0 +1,239 @@
1
+ """A request as it arrived, with everything the server learned alongside it."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Protocol, Self, runtime_checkable
6
+
7
+ from .request_interface import RequestInterface
8
+
9
+ if TYPE_CHECKING:
10
+ from collections.abc import Mapping
11
+
12
+ __all__ = ["ServerRequestInterface"]
13
+
14
+
15
+ @runtime_checkable
16
+ class ServerRequestInterface(RequestInterface, Protocol):
17
+ """An incoming, server-side request.
18
+
19
+ On top of what every request carries — a protocol version, a method, a
20
+ URI, headers and a body — this one gathers everything that reached the
21
+ application with it:
22
+
23
+ - the parameters of the environment it arrived in;
24
+ - the cookies the client sent;
25
+ - the query string, parsed;
26
+ - the files that came with it, if any;
27
+ - the body, parsed into parameters.
28
+
29
+ The environment parameters are the state the request arrived in and
30
+ nothing may change them, which is why there is no method to. The rest can
31
+ all be rebuilt from the environment or from the body — a body may need
32
+ parsing differently once its content type is known, for one — so each of
33
+ those does have a method.
34
+
35
+ A request is also worth annotating as it is handled: a path matched into
36
+ named parameters, a cookie decrypted, an authorization header resolved to
37
+ a user. Those findings go in the attributes.
38
+
39
+ Requests are immutable. Every ``with_*`` method keeps the instance it was
40
+ called on as it was and returns one carrying the change.
41
+ """
42
+
43
+ def get_server_params(self) -> Mapping[str, object]:
44
+ """Return the parameters of the environment the request arrived in.
45
+
46
+ Where they came from is nobody's business but the implementation's:
47
+ they need not describe a server process at all.
48
+
49
+ Returns:
50
+ The environment parameters, each under the name the environment
51
+ gave it.
52
+ """
53
+ ...
54
+
55
+ def get_cookie_params(self) -> Mapping[str, str]:
56
+ """Return the cookies the client sent.
57
+
58
+ Returns:
59
+ Each cookie name mapped to its value.
60
+ """
61
+ ...
62
+
63
+ def with_cookie_params(self, cookies: Mapping[str, str]) -> Self:
64
+ """Return an instance carrying ``cookies``.
65
+
66
+ The cookies need not be the ones that arrived; they are usually
67
+ supplied when the request is built.
68
+
69
+ Neither the ``Cookie`` header of the new instance nor its environment
70
+ parameters change with them.
71
+
72
+ Args:
73
+ cookies: Each cookie name mapped to its value.
74
+
75
+ Returns:
76
+ A new instance; this one is left as it was.
77
+ """
78
+ ...
79
+
80
+ def get_query_params(self) -> Mapping[str, object]:
81
+ """Return the query string, parsed into parameters.
82
+
83
+ These may have drifted from the URI and from the environment
84
+ parameters, since nothing keeps the three in step. To be sure of
85
+ reading what arrived, parse ``get_uri().get_query()``, or the query
86
+ string among the environment parameters, instead.
87
+
88
+ Returns:
89
+ Each parameter name mapped to its value: a string, or a nested
90
+ structure where the name repeats or nests.
91
+ """
92
+ ...
93
+
94
+ def with_query_params(self, query: Mapping[str, object]) -> Self:
95
+ """Return an instance carrying ``query``.
96
+
97
+ The parameters should not change over the course of the request. They
98
+ may be supplied when the request is built, or derived from something
99
+ else such as the URI — and where they are parsed out of the URI, how
100
+ a repeated name and how a nested name come out must match what
101
+ :meth:`get_query_params` promises.
102
+
103
+ Neither the URI the request holds nor its environment parameters
104
+ change with them.
105
+
106
+ Args:
107
+ query: Each parameter name mapped to its value.
108
+
109
+ Returns:
110
+ A new instance; this one is left as it was.
111
+ """
112
+ ...
113
+
114
+ def get_uploaded_files(self) -> Mapping[str, object]:
115
+ """Return the files that came with the request.
116
+
117
+ The files are arranged in a tree that follows the names of the fields
118
+ they were submitted under, every leaf of it an
119
+ :class:`~xtr_http_message_contracts.uploaded_file_interface.UploadedFileInterface`.
120
+
121
+ They may have been gathered from the environment or from the body when
122
+ the request was built, or supplied through
123
+ :meth:`with_uploaded_files`.
124
+
125
+ Returns:
126
+ The tree of uploaded files. No files at all gives an empty
127
+ mapping.
128
+ """
129
+ ...
130
+
131
+ def with_uploaded_files(self, uploaded_files: Mapping[str, object]) -> Self:
132
+ """Return an instance carrying ``uploaded_files``.
133
+
134
+ Args:
135
+ uploaded_files: A tree of uploaded files, shaped as
136
+ :meth:`get_uploaded_files` describes.
137
+
138
+ Returns:
139
+ A new instance; this one is left as it was.
140
+
141
+ Raises:
142
+ ValueError: When the tree is not shaped that way.
143
+ """
144
+ ...
145
+
146
+ def get_parsed_body(self) -> object | None:
147
+ """Return the parameters found in the body of the request.
148
+
149
+ A ``POST`` whose content type is form-encoded or a multipart form must
150
+ answer with the submitted form fields.
151
+
152
+ Anything else may answer with whatever parsing the body yielded.
153
+ Parsing yields structure, so what comes back is a mapping or an object
154
+ — never a scalar.
155
+
156
+ Returns:
157
+ The parsed body parameters, or ``None`` when the request has no
158
+ body to parse.
159
+ """
160
+ ...
161
+
162
+ def with_parsed_body(self, data: object | None) -> Self:
163
+ """Return an instance carrying ``data`` as its body parameters.
164
+
165
+ The parameters may be supplied when the request is built. Where the
166
+ content type is form-encoded or a multipart form and the method is
167
+ ``POST``, this method is for the submitted form fields and nothing
168
+ else.
169
+
170
+ The data need not have come from a form, but it must be what parsing
171
+ the body yielded. Parsing yields structure, so only a mapping or an
172
+ object is accepted — or ``None`` when there was nothing to parse.
173
+
174
+ A request whose content was negotiated to be a JSON payload, for
175
+ instance, can be given the deserialised payload this way.
176
+
177
+ Args:
178
+ data: The parsed body parameters, or ``None``.
179
+
180
+ Returns:
181
+ A new instance; this one is left as it was.
182
+
183
+ Raises:
184
+ ValueError: When the data is of a kind that cannot be body
185
+ parameters.
186
+ """
187
+ ...
188
+
189
+ def get_attributes(self) -> Mapping[str, object]:
190
+ """Return what was derived from the request while handling it.
191
+
192
+ Anything at all: the named parameters a path matched, the plaintext of
193
+ a cookie, the result of parsing a body that was not a form. They
194
+ belong to the application and to the request, and may change over its
195
+ course.
196
+
197
+ Returns:
198
+ Each attribute name mapped to its value.
199
+ """
200
+ ...
201
+
202
+ def get_attribute(self, name: str, default: object | None = None) -> object | None:
203
+ """Return one of the attributes :meth:`get_attributes` describes.
204
+
205
+ Being able to name what an absent attribute should read as is why
206
+ there is no method for asking whether one is there.
207
+
208
+ Args:
209
+ name: The attribute name.
210
+ default: What to answer with when the request carries no such
211
+ attribute.
212
+
213
+ Returns:
214
+ The value under ``name``, or ``default``.
215
+ """
216
+ ...
217
+
218
+ def with_attribute(self, name: str, value: object) -> Self:
219
+ """Return an instance carrying one more of the attributes :meth:`get_attributes` describes.
220
+
221
+ Args:
222
+ name: The attribute name.
223
+ value: The value to record under it.
224
+
225
+ Returns:
226
+ A new instance; this one is left as it was.
227
+ """
228
+ ...
229
+
230
+ def without_attribute(self, name: str) -> Self:
231
+ """Return an instance with the ``name`` attribute gone.
232
+
233
+ Args:
234
+ name: The attribute name.
235
+
236
+ Returns:
237
+ A new instance; this one is left as it was.
238
+ """
239
+ ...
@@ -0,0 +1,191 @@
1
+ """A stream of bytes a message body is read from and written to."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
7
+
8
+ if TYPE_CHECKING:
9
+ from typing import BinaryIO
10
+
11
+ __all__ = ["StreamInterface"]
12
+
13
+
14
+ @runtime_checkable
15
+ class StreamInterface(Protocol):
16
+ """A data stream, usually wrapping an open file object.
17
+
18
+ This is the body of every message: a cursor over bytes, with the questions
19
+ worth asking before moving it — is it seekable, is it readable, is it
20
+ writable.
21
+
22
+ Moving the cursor is awaited. :meth:`read`, :meth:`write`,
23
+ :meth:`get_contents`, :meth:`seek`, :meth:`rewind` and :meth:`close` do
24
+ input and output, so a body can be fed by a socket as readily as by a
25
+ file, without blocking whoever is waiting on it. The questions above only
26
+ report what the stream already holds, so they cost no ``await``.
27
+
28
+ Unlike the messages that carry it, a stream is *not* immutable: reading,
29
+ writing and seeking all move the cursor in place.
30
+ """
31
+
32
+ async def close(self) -> None:
33
+ """Close the stream and release whatever it was holding open."""
34
+ ...
35
+
36
+ def detach(self) -> BinaryIO | None:
37
+ """Hand the underlying file object out and leave the stream unusable.
38
+
39
+ Once detached, nothing else on this stream can be relied on; the
40
+ caller owns what came back.
41
+
42
+ Returns:
43
+ The file object the stream wrapped, or ``None`` when it wrapped
44
+ none.
45
+ """
46
+ ...
47
+
48
+ def get_size(self) -> int | None:
49
+ """Return the size of the stream in bytes, when that is known.
50
+
51
+ Returns:
52
+ The size in bytes, or ``None`` when the stream cannot say.
53
+ """
54
+ ...
55
+
56
+ def tell(self) -> int:
57
+ """Return where the cursor currently sits.
58
+
59
+ Returns:
60
+ The cursor's offset in bytes from the beginning of the stream.
61
+
62
+ Raises:
63
+ RuntimeError: When the position cannot be read.
64
+ """
65
+ ...
66
+
67
+ def eof(self) -> bool:
68
+ """Tell whether the cursor has reached the end of the stream.
69
+
70
+ Returns:
71
+ ``True`` once the end has been reached.
72
+ """
73
+ ...
74
+
75
+ def is_seekable(self) -> bool:
76
+ """Tell whether the cursor can be moved.
77
+
78
+ Returns:
79
+ ``True`` when :meth:`seek` and :meth:`rewind` work on this stream.
80
+ """
81
+ ...
82
+
83
+ async def seek(self, offset: int, whence: int = os.SEEK_SET) -> None:
84
+ """Move the cursor to a position in the stream.
85
+
86
+ Args:
87
+ offset: How far to move, in bytes.
88
+ whence: What ``offset`` counts from: ``os.SEEK_SET`` makes it an
89
+ absolute position, ``os.SEEK_CUR`` adds it to where the cursor
90
+ is, ``os.SEEK_END`` adds it to the end of the stream.
91
+
92
+ Raises:
93
+ RuntimeError: When the cursor cannot be moved.
94
+ """
95
+ ...
96
+
97
+ async def rewind(self) -> None:
98
+ """Move the cursor back to the beginning of the stream.
99
+
100
+ Equivalent to ``await seek(0)`` on a seekable stream.
101
+
102
+ Raises:
103
+ RuntimeError: When the stream is not seekable, or the cursor
104
+ cannot be moved.
105
+ """
106
+ ...
107
+
108
+ def is_writable(self) -> bool:
109
+ """Tell whether data can be written to the stream.
110
+
111
+ Returns:
112
+ ``True`` when :meth:`write` works on this stream.
113
+ """
114
+ ...
115
+
116
+ async def write(self, data: bytes) -> int:
117
+ """Write bytes at the cursor.
118
+
119
+ Args:
120
+ data: What to write.
121
+
122
+ Returns:
123
+ How many bytes were written.
124
+
125
+ Raises:
126
+ RuntimeError: When the data cannot be written.
127
+ """
128
+ ...
129
+
130
+ def is_readable(self) -> bool:
131
+ """Tell whether data can be read from the stream.
132
+
133
+ Returns:
134
+ ``True`` when :meth:`read` and :meth:`get_contents` work on this
135
+ stream.
136
+ """
137
+ ...
138
+
139
+ async def read(self, length: int) -> bytes:
140
+ """Read up to ``length`` bytes from the cursor.
141
+
142
+ Fewer than ``length`` bytes may come back, whenever the underlying
143
+ file object returns fewer.
144
+
145
+ Args:
146
+ length: The most to read.
147
+
148
+ Returns:
149
+ What was read, or empty bytes when nothing was available.
150
+
151
+ Raises:
152
+ RuntimeError: When the stream cannot be read.
153
+ """
154
+ ...
155
+
156
+ async def get_contents(self) -> bytes:
157
+ """Read the whole of the stream, from the first byte to the last.
158
+
159
+ Rewinds first when the stream is seekable, then reads to the end. On a
160
+ stream that cannot be rewound there is nothing to rewind to, so this
161
+ reads from wherever the cursor sits; :meth:`read` is the way to take a
162
+ measured amount from the current position instead.
163
+
164
+ Beware: this may pull a very large amount of data into memory.
165
+
166
+ Returns:
167
+ Every byte in the stream.
168
+
169
+ Raises:
170
+ RuntimeError: When the stream cannot be read, or reading fails
171
+ part way. An unreadable body is reported rather than answered
172
+ with empty bytes, which would be indistinguishable from an
173
+ empty one.
174
+ """
175
+ ...
176
+
177
+ def get_metadata(self, key: str | None = None) -> object:
178
+ """Return what the stream knows about itself.
179
+
180
+ The keys are those of the underlying file object — ``mode``,
181
+ ``seekable`` and ``uri`` among them.
182
+
183
+ Args:
184
+ key: One entry to look up. ``None`` asks for all of them.
185
+
186
+ Returns:
187
+ A mapping of every entry when ``key`` is ``None``; otherwise the
188
+ value under ``key``, or ``None`` when the stream carries no such
189
+ entry.
190
+ """
191
+ ...
@@ -0,0 +1,45 @@
1
+ """What went wrong, or did not, while a file was being uploaded."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from enum import IntEnum
6
+
7
+ __all__ = ["UploadError"]
8
+
9
+
10
+ class UploadError(IntEnum):
11
+ """The outcome an uploaded file reports from :meth:`get_error`.
12
+
13
+ The standard this package translates describes the outcome as one of a set
14
+ of numbered constants its host language defines. Nothing here defines
15
+ them, so they are gathered into this enumeration, keeping the numbers the
16
+ wire and the standard already agree on — which is why ``5`` is missing:
17
+ that number was never assigned.
18
+
19
+ Being an :class:`~enum.IntEnum`, a member compares and passes as the
20
+ integer the contract calls for, so an implementation may hold either.
21
+ """
22
+
23
+ OK = 0
24
+ """The file arrived whole; nothing went wrong."""
25
+
26
+ INI_SIZE = 1
27
+ """The file was larger than the limit the server configuration allows."""
28
+
29
+ FORM_SIZE = 2
30
+ """The file was larger than the limit the submitted form itself named."""
31
+
32
+ PARTIAL = 3
33
+ """The upload stopped part way; only some of the file arrived."""
34
+
35
+ NO_FILE = 4
36
+ """The field was submitted with no file in it."""
37
+
38
+ NO_TMP_DIR = 6
39
+ """There was nowhere to put the incoming file while it was being received."""
40
+
41
+ CANT_WRITE = 7
42
+ """The incoming file could not be written to where it was being kept."""
43
+
44
+ EXTENSION = 8
45
+ """Something the server had loaded refused the upload."""
@@ -0,0 +1,110 @@
1
+ """A file that came in with a request."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING, Protocol, runtime_checkable
6
+
7
+ if TYPE_CHECKING:
8
+ from .stream_interface import StreamInterface
9
+
10
+ __all__ = ["UploadedFileInterface"]
11
+
12
+
13
+ @runtime_checkable
14
+ class UploadedFileInterface(Protocol):
15
+ """One uploaded file, as a value: what arrived, how much of it, and from where.
16
+
17
+ Instances are immutable — nothing here returns a changed copy, and nothing
18
+ changes the file in place except :meth:`move_to`, which is the one
19
+ operation that consumes it and, because it does input and output, the one
20
+ that is awaited.
21
+ """
22
+
23
+ def get_stream(self) -> StreamInterface:
24
+ """Return the contents of the file as a stream.
25
+
26
+ Reading it as a stream is what lets the file be copied anywhere a
27
+ stream can be written to.
28
+
29
+ Returns:
30
+ The contents of the uploaded file.
31
+
32
+ Raises:
33
+ RuntimeError: When there is no stream to be had — :meth:`move_to`
34
+ having already taken the file away, among other reasons.
35
+ """
36
+ ...
37
+
38
+ async def move_to(self, target_path: str) -> None:
39
+ """Move the file to ``target_path``, consuming it.
40
+
41
+ The path may be absolute or relative; a relative one is resolved the
42
+ way the file system calls of the host resolve one.
43
+
44
+ Whatever held the file is gone once the move completes, which is why
45
+ calling it a second time is an error rather than a second move.
46
+
47
+ To put the file somewhere a path cannot name, read :meth:`get_stream`
48
+ and write that where it needs to go.
49
+
50
+ Args:
51
+ target_path: Where to move the file to.
52
+
53
+ Raises:
54
+ ValueError: When the target path is not a usable one.
55
+ RuntimeError: When the move fails, or when the file has already
56
+ been moved.
57
+ """
58
+ ...
59
+
60
+ def get_size(self) -> int | None:
61
+ """Return the size of the file in bytes.
62
+
63
+ The size reported should be the one recorded as the file arrived,
64
+ counted from what was actually received.
65
+
66
+ Returns:
67
+ The size in bytes, or ``None`` when it is not known.
68
+ """
69
+ ...
70
+
71
+ def get_error(self) -> int:
72
+ """Return how the upload went.
73
+
74
+ The value is one of
75
+ :class:`~xtr_http_message_contracts.upload_error.UploadError`, and it
76
+ is :attr:`~xtr_http_message_contracts.upload_error.UploadError.OK`
77
+ when the file arrived whole. The value recorded as the file arrived is
78
+ the one that should come back.
79
+
80
+ Returns:
81
+ The outcome of the upload.
82
+ """
83
+ ...
84
+
85
+ def get_client_filename(self) -> str | None:
86
+ """Return the file name the client sent.
87
+
88
+ Do not trust it. It is whatever the client chose to send, and a client
89
+ may well have chosen it to break something.
90
+
91
+ The name recorded as the file arrived is the one that should come
92
+ back.
93
+
94
+ Returns:
95
+ The file name the client sent, or ``None`` when it sent none.
96
+ """
97
+ ...
98
+
99
+ def get_client_media_type(self) -> str | None:
100
+ """Return the media type the client sent.
101
+
102
+ Do not trust it either, and for the same reason.
103
+
104
+ The media type recorded as the file arrived is the one that should
105
+ come back.
106
+
107
+ Returns:
108
+ The media type the client sent, or ``None`` when it sent none.
109
+ """
110
+ ...