xtr_http_message ¶
The HTTP message contract, implemented: six classes and the factory that builds them.
A library that handles requests should depend on the contract alone. An application has to pick something that is a request, and this is that something: small, strict, and tied to no web framework.
What is here is one class per interface, and nothing besides:
- :class:
~xtr_http_message.request.Request— a request going out: a method, a URI, headers and a body, with theHostheader taken from the URI. - :class:
~xtr_http_message.server_request.ServerRequest— a request that arrived, with the environment parameters, the cookies, the query string parsed, the files that came with it, the parsed body and the attributes a handler annotates it with. Born complete, or born connected over a :class:~xtr_http_message.request_source.RequestSource— a connection whose body side arrives as it is read. - :class:
~xtr_http_message.response.Response— a status code, the reason phrase recommended for it, headers and a body. - :class:
~xtr_http_message.stream.Stream— a body, as a cursor over bytes behind an open binary file object. - :class:
~xtr_http_message.lazy_stream.LazyStream— a body that stands in unread: the whole of it is read once, on the first read, and buffered after. - :class:
~xtr_http_message.uri.Uri— a URI taken apart into components and put back together as text. - :class:
~xtr_http_message.uploaded_file.UploadedFile— one file that came in with a request, movable once. - :class:
~xtr_http_message.factory.http_factory.HttpFactory— all six factory interfaces behind one object.
from xtr_http_message import Response, ServerRequest
request = ServerRequest("GET", "https://example.com/orders?page=2")
assert request.get_query_params() == {"page": "2"}
response = Response(201, {"content-type": "application/json"}, b'{"id": 7}')
assert response.get_reason_phrase() == "Created"
Every message is immutable: a with_* method leaves the instance it was
called on alone and returns one carrying the change — and hands the same
instance back when the change would change nothing. A stream is the one thing
that is not: reading, writing and seeking move its cursor in place. Its
payload is bytes throughout, so await stream.get_contents() is how the
whole of a body is read; there is no encoding to guess at.
Bridging a message to the web framework an application runs on belongs with that framework's integration, not here.
HttpMessageError ¶
Bases: Exception
Something went wrong building or using a message, a stream or a URI.
Nothing raises this class itself; it exists so that an application can
catch everything this package raises with one except clause, whichever
of the four concrete errors reached it.
InvalidArgumentError ¶
Bases: HttpMessageError, ValueError
An argument's value rules it out: a malformed header name, an out-of-range port.
It derives from :class:ValueError as well as from
:class:~xtr_http_message.exception.http_message_error.HttpMessageError
because that is what the contract promises a caller: code written against
the interfaces catches the builtin and never names this package.
StreamError ¶
Bases: HttpMessageError, RuntimeError
A stream operation cannot be carried out: detached, not seekable, not readable.
It derives from :class:RuntimeError as well as from
:class:~xtr_http_message.exception.http_message_error.HttpMessageError
because that is what the contract promises a caller: code written against
the interfaces catches the builtin and never names this package.
UploadedFileError ¶
Bases: HttpMessageError, RuntimeError
An uploaded file is unusable: the upload failed, or the file is already moved.
It derives from :class:RuntimeError as well as from
:class:~xtr_http_message.exception.http_message_error.HttpMessageError
because that is what the contract promises a caller: code written against
the interfaces catches the builtin and never names this package.
HttpFactory ¶
Bases: RequestFactoryInterface, ResponseFactoryInterface, ServerRequestFactoryInterface, StreamFactoryInterface, UploadedFileFactoryInterface, UriFactoryInterface
Builds every kind of message this package implements.
One object rather than six, because the six belong together: a library given this one can build whatever it needs, and an application that wants to swap the implementation out swaps one registration.
from xtr_http_message.factory import HttpFactory
factory = HttpFactory()
response = factory.create_response(404)
assert response.get_reason_phrase() == "Not Found"
It holds no state, so one instance serves a whole application.
create_request ¶
Return a new request for method and uri.
Parameters:
-
method(str) –The HTTP method of the request.
-
uri(UriInterface | str) –The URI of the request. Given as text, it is read into one.
Returns:
-
RequestInterface–The request.
create_response ¶
Return a new response for code.
Parameters:
-
code(int, default:200) –The status code.
-
reason_phrase(str | None, default:None) –The phrase to go with
code. Left out, the recommended phrase for the code is filled in where there is one; given as an empty string, the response carries no phrase at all. That is the difference between asking for the usual phrase and asking for none.
Returns:
-
ResponseInterface–The response.
create_server_request ¶
create_server_request(method: str, uri: UriInterface | str, server_params: Mapping[str, object] | None = None) -> ServerRequestInterface
Return a new server request for method and uri.
The environment parameters are taken exactly as given: nothing in them is read, and in particular neither the method nor the URI, which is why both have to be passed.
Parameters:
-
method(str) –The HTTP method of the request.
-
uri(UriInterface | str) –The URI of the request. Given as text, it is read into one.
-
server_params(Mapping[str, object] | None, default:None) –The environment parameters to seed the request with.
Noneseeds it with none.
Returns:
-
ServerRequestInterface–The server request.
create_stream ¶
Return a new stream over content, held in memory.
Parameters:
-
content(bytes, default:b'') –The bytes the stream reads back.
Returns:
-
StreamInterface–The stream, with its cursor at the first byte.
create_stream_from_file ¶
Return a new stream over the file at filename.
Parameters:
-
filename(str) –The path to open.
-
mode(str, default:'r') –How to open it. The payload is bytes, so the mode is taken as a binary one whether or not it says so.
Returns:
-
StreamInterface–The stream.
Raises:
-
InvalidArgumentError–When the mode is not a mode.
-
StreamError–When the path is empty, or the file cannot be opened.
create_stream_from_resource ¶
Return a new stream over an open binary file object.
Parameters:
-
resource(BinaryIO) –The file object. The stream takes it over: closing the stream closes it.
Returns:
-
StreamInterface–The stream.
create_uploaded_file ¶
create_uploaded_file(stream: StreamInterface, size: int | None = None, error: int = UploadError.OK, client_filename: str | None = None, client_media_type: str | None = None) -> UploadedFileInterface
Return a new uploaded file reading from stream.
Parameters:
-
stream(StreamInterface) –The contents of the uploaded file.
-
size(int | None, default:None) –The size in bytes. Left out, it is read off the stream.
-
error(int, default:OK) –How the upload went.
-
client_filename(str | None, default:None) –The file name the client sent, if any.
-
client_media_type(str | None, default:None) –The media type the client sent, if any.
Returns:
-
UploadedFileInterface–The uploaded file.
Raises:
-
InvalidArgumentError–When
erroris not one of the upload outcomes.
create_uri ¶
Return a new URI read from uri.
Parameters:
-
uri(str, default:'') –The URI as text. Empty builds one with no component at all.
Returns:
-
UriInterface–The URI.
Raises:
-
InvalidArgumentError–When the text cannot be read as a URI.
LazyStream ¶
Bases: StreamInterface
A body stream that reads its bytes once, on its first read.
Built with a coroutine that returns the buffered body — one that
reads the connection and parses it per its content type — and holds
nothing until the first :meth:read or :meth:get_contents calls
it. From then on it is a plain view over the buffer, and every
question the contract asks of an unread stream is answered for the
buffer it will be.
Read the body through materialise, when anything first asks to.
Parameters:
close
async
¶
Close the buffer, if there is one to close.
An unread body holds nothing open, so closing one before the first read is not a read: it is a no-op, and the next reader still gets the bytes off the connection.
detach ¶
Hand out the buffer's file object, or None while there is none.
get_size ¶
Return the size of the buffered body, or None before there is one.
is_seekable ¶
Tell whether the cursor moves: the buffer it will be is over bytes in memory.
seek
async
¶
Move the cursor, materialising the body if nothing has read it yet.
Raises:
-
StreamError–When the buffer cannot be moved, once there is one.
rewind
async
¶
Move the cursor back to the first byte, materialising if nothing has read.
is_writable ¶
Tell whether bytes can be written to the buffer: it is a buffer, so yes.
write
async
¶
Write at the cursor, materialising the body if nothing has read it yet.
Raises:
-
StreamError–When the buffer cannot be written to.
is_readable ¶
Tell whether bytes can be read: they can, once anything has been read.
read
async
¶
Read up to length bytes, materialising the body if nothing has read it yet.
Raises:
-
StreamError–When the buffer cannot be read.
get_contents
async
¶
Return every byte of the body, materialising it if nothing has read it yet.
Raises:
-
StreamError–When the buffer cannot be read.
get_metadata ¶
Return what the buffer knows about itself, or nothing while there is none.
Request ¶
Request(method: str, uri: UriInterface | str, headers: Mapping[str, str | Sequence[str]] | None = None, body: bytes | BinaryIO | StreamInterface | None = None, version: str = '1.1')
Bases: RequestTrait, RequestInterface
An outgoing, client-side request: a method, a URI, headers and a body.
from xtr_http_message import Request
request = Request("GET", "https://example.com/orders?page=2")
assert request.get_header_line("host") == "example.com"
assert request.get_request_target() == "/orders?page=2"
The Host header is taken from the URI unless one was given with the
request, and is sent in front of every other header.
Build a request.
Parameters:
-
method(str) –The HTTP method, kept exactly as given.
-
uri(UriInterface | str) –The URI of the request. Given as text, it is read into a :class:
~xtr_http_message.uri.Uri. -
headers(Mapping[str, str | Sequence[str]] | None, default:None) –Each header name mapped to one value or to several.
-
body(bytes | BinaryIO | StreamInterface | None, default:None) –The payload, in any of the shapes a stream is built from. Left out, nothing is opened until the body is asked for.
-
version(str, default:'1.1') –The HTTP version number alone.
Raises:
-
InvalidArgumentError–When the URI cannot be read, or a header name or value is not one.
RequestSource ¶
Bases: Protocol
Where a connected request reads its late answers from.
A request built over a connection materialises its body side lazily: the sync getters answer what materialisation has yielded so far, and the body stream reads the rest through here on its first read. The head — method, URI, headers, cookies, query, environment — never comes from here: it is passed eagerly when the request is built, because it costs no input and never changes mid-request.
materialise
async
¶
Read the whole body once, and answer its bytes.
Runs at most once — the implementation memoises — filling the parsed side and the uploaded files as a side effect, so the sync peeks answer from then on. The bytes answered are the raw body bytes: for a submitted form, the raw form bytes, with the form itself landing in the parsed side.
Returns:
-
bytes–The raw bytes of the body.
parsed_body ¶
Return what parsing the body yielded, or None until it has.
A sync peek at what :meth:materialise has yielded so far: the
form for form content types, a JSON object for JSON, None
before any body read.
uploaded_files ¶
Return the files that came with the body, empty until it is read.
A sync peek, as :meth:parsed_body is one: the files are
gathered when the body is materialised, so before any body read
this answers an empty mapping.
attributes ¶
Return what has been derived from the request while handling it.
A live view: routing fills the named path parameters after the request exists, and each read answers them as they are now.
Response ¶
Response(status: int = 200, headers: Mapping[str, str | Sequence[str]] | None = None, body: bytes | BinaryIO | StreamInterface | None = None, version: str = '1.1', reason: str | None = None)
Bases: MessageTrait, ResponseInterface
A response: a status code, the phrase that goes with it, headers and a body.
from xtr_http_message import Response
response = Response(201, {"content-type": "application/json"}, b'{"id": 7}')
assert response.get_reason_phrase() == "Created"
Given no reason phrase, the one recommended for the status code is filled in; given an empty one, the response carries none, since a status line need not have a phrase at all.
Build a response.
Parameters:
-
status(int, default:200) –The status code.
-
headers(Mapping[str, str | Sequence[str]] | None, default:None) –Each header name mapped to one value or to several.
-
body(bytes | BinaryIO | StreamInterface | None, default:None) –The payload, in any of the shapes a stream is built from. Left out, nothing is opened until the body is asked for.
-
version(str, default:'1.1') –The HTTP version number alone.
-
reason(str | None, default:None) –The reason phrase.
None— the default — takes the one recommended forstatus; an empty string leaves the response with none.
Raises:
-
InvalidArgumentError–When a header name or value is not one.
get_status_code ¶
get_reason_phrase ¶
with_status ¶
Return an instance carrying code and, optionally, reason_phrase.
Parameters:
-
code(int) –The status code to set.
-
reason_phrase(str, default:'') –The phrase to go with
code. Left out or empty, the one recommended forcodeis filled in where there is one.
Returns:
-
Self–A new instance; this one is left as it was.
Raises:
-
InvalidArgumentError–When the code is not a status code.
ServerRequest ¶
ServerRequest(method: str, uri: UriInterface | str, headers: Mapping[str, str | Sequence[str]] | None = None, body: bytes | BinaryIO | StreamInterface | None = None, version: str = '1.1', server_params: Mapping[str, object] | None = None)
Bases: ConnectedTrait, ServerRequestInterface
An incoming, server-side request.
On top of what every request carries, this one gathers what reached the application with it: the parameters of the environment it arrived in, the cookies, the query string parsed, the files that came with it and the body parsed into parameters — plus the attributes a handler annotates it with as it works out who sent it and what they asked for.
from xtr_http_message import ServerRequest
request = ServerRequest("GET", "/orders?page=2")
assert request.get_query_params() == {"page": "2"}
assert request.with_attribute("user", "ada").get_attribute("user") == "ada"
The query parameters are read off the URI as the request is built; nothing keeps them in step with it afterwards, so a URI changed later leaves them as they were — which is what lets a handler correct them.
The cookies, the query parameters and the uploaded files are held exactly
as they were given when nothing can change them — a mapping that is not a
:class:~collections.abc.MutableMapping — and copied when they can. So a
mapping of a kind that answers more than a single value per name reaches
whoever reads it back as that kind, rather than flattened into a plain
one.
A request is also born connected, over a
:class:~xtr_http_message.request_source.RequestSource — see
:meth:over. Its head is passed eagerly; its body is one lazy stream
that materialises on first read; its parsed body, uploaded files and
attributes answer what the source has yielded so far, the attributes
live. The with_* members of such a request detach: the copy is
eager in everything a handler can change — the head as it was passed,
the attributes a snapshot — so a change a handler makes never reaches
the connection. Its parsed body and uploaded files stay linked to the
source until :meth:with_parsed_body or :meth:with_uploaded_files
gives the copy its own: a listener is handed a copy before anything has
read the body, and a read made after the copy — through it, through the
request or through any other copy — is answered by the copy too.
Build a server request.
Parameters:
-
method(str) –The HTTP method, kept exactly as given.
-
uri(UriInterface | str) –The URI of the request. Given as text, it is read into a :class:
~xtr_http_message.uri.Uri. -
headers(Mapping[str, str | Sequence[str]] | None, default:None) –Each header name mapped to one value or to several.
-
body(bytes | BinaryIO | StreamInterface | None, default:None) –The payload, in any of the shapes a stream is built from. Left out, nothing is opened until the body is asked for.
-
version(str, default:'1.1') –The HTTP version number alone.
-
server_params(Mapping[str, object] | None, default:None) –The parameters of the environment the request arrived in, taken exactly as given.
Nonemeans none.
Raises:
-
InvalidArgumentError–When the URI cannot be read, or a header name or value is not one.
over
classmethod
¶
over(method: str, uri: UriInterface | str, *, source: RequestSource, body: bytes | BinaryIO | StreamInterface | None = None, headers: Mapping[str, str | Sequence[str]] | None = None, server_params: Mapping[str, object] | None = None, cookies: Mapping[str, str] | None = None, query: Mapping[str, object] | None = None, protocol_version: str = '1.1') -> Self
Build a server request over source, born connected to it.
The head is passed eagerly — it costs no input and never changes mid-request — and the body side comes from the source: the body is one lazy stream that materialises on its first read, and the parsed body and the uploaded files answer what materialisation has yielded so far.
Parameters:
-
method(str) –The HTTP method, kept exactly as given.
-
uri(UriInterface | str) –The URI of the request. Given as text, it is read into a :class:
~xtr_http_message.uri.Uri. -
source(RequestSource) –Where the connected request reads its late answers from.
-
body(bytes | BinaryIO | StreamInterface | None, default:None) –Refused — the body of a request built over a source is the source's to materialise, and there is one owner of the body. The parameter exists so a caller used to the constructor's shape is told the rule rather than left with an unexpected keyword.
-
headers(Mapping[str, str | Sequence[str]] | None, default:None) –Each header name mapped to one value or to several. A header the message grammar refuses is left out rather than refusing the request: a connection let it through, and a message is no place to re-litigate that.
-
server_params(Mapping[str, object] | None, default:None) –The parameters of the environment the request arrived in, taken exactly as given.
-
cookies(Mapping[str, str] | None, default:None) –The cookies the client sent; left out, none.
-
query(Mapping[str, object] | None, default:None) –The query string, parsed into parameters; left out, the URI's own query stands.
-
protocol_version(str, default:'1.1') –The HTTP version number alone.
Returns:
-
Self–The request, connected to
source.
Raises:
-
InvalidArgumentError–When
bodyis given alongsidesource.
get_server_params ¶
Return the parameters of the environment the request arrived in.
Returns:
get_cookie_params ¶
with_cookie_params ¶
get_query_params ¶
Return the query string, parsed into parameters.
Returns:
-
Mapping[str, object]–Each parameter name mapped to its value — the mapping as it was
-
Mapping[str, object]–given where nothing can change it, otherwise a fresh one. These
-
Mapping[str, object]–were read off the URI when the request was built and may have been
-
Mapping[str, object]–replaced since; parse
get_uri().get_query()to be sure of what -
Mapping[str, object]–arrived.
with_query_params ¶
get_uploaded_files ¶
Return the files that came with the request.
Returns:
-
Mapping[str, object]–A mapping shaped like the names the files were submitted under,
-
Mapping[str, object]–every leaf of it an uploaded file — the mapping as it was given
-
Mapping[str, object]–where nothing can change it, otherwise a fresh one. Empty when no
-
Mapping[str, object]–file came with the request. A request built over a connection
-
Mapping[str, object]–answers what its body's materialisation has gathered so far:
-
Mapping[str, object]–empty until the body has been read — and so does a copy of one,
-
Mapping[str, object]–until it is given files of its own.
with_uploaded_files ¶
get_parsed_body ¶
Return the parameters found in the body of the request.
Returns:
-
object | None–Whatever parsing the body yielded, or
Nonewhen nothing has -
object | None–been parsed into the request. A request built over a connection
-
object | None–answers what its body's materialisation has yielded so far:
-
object | None–Noneuntil the body has been read — and so does a copy of -
object | None–one, until it is given a parsed body of its own.
with_parsed_body ¶
Return an instance carrying data as its body parameters.
Parameters:
-
data(object | None) –The parsed body parameters — a mapping, or an object standing for the structure the body held — or
Nonewhen there was nothing to parse.
Returns:
-
Self–A new instance answering
datafrom now on, however late the -
Self–body of the connection it was copied from is read; this one is
-
Self–left as it was.
Raises:
-
InvalidArgumentError–When the data is a scalar: parsing a body yields structure, so a number or a string cannot be what it yielded.
get_attributes ¶
Return what was derived from the request while handling it.
Returns:
-
Mapping[str, object]–A fresh mapping of each attribute name to its value. A request
-
Mapping[str, object]–built over a connection reads them live, off its source: the
-
Mapping[str, object]–named parameters the matched route fills in are there as soon
-
Mapping[str, object]–as routing has filled them — which is after the request exists.
get_attribute ¶
Return one of the attributes :meth:get_attributes describes.
An attribute recorded as None is told apart from one that was
never recorded: the first reads as None, the second as
default.
Parameters:
-
name(str) –The attribute name.
-
default(object | None, default:None) –What to answer with when the request carries no such attribute.
Returns:
-
object | None–The value under
name, ordefault.
with_attribute ¶
Stream ¶
Bases: StreamInterface
A stream over an open binary file object.
Build one with :meth:create rather than by hand: that is the entry point
that takes the payload in any of the three shapes a body arrives in —
bytes, an open file object, or a stream that is already one of these.
The payload is bytes throughout. A body may be an image or a compressed
archive, so there is no encoding to guess at, and
await stream.get_contents() is what reads the whole of one.
Moving bytes is awaited: :meth:read, :meth:write,
:meth:get_contents, :meth:seek, :meth:rewind and :meth:close do
input and output. The methods that only report what the stream already
holds cost no await.
Unlike the messages that carry it, a stream is not immutable: reading, writing and seeking all move its cursor in place.
Wrap an open binary file object.
Parameters:
-
body(BinaryIO) –The file object to read from and write to. The stream takes it over: closing the stream closes it.
create
classmethod
¶
Return a stream over body, whatever shape it arrived in.
Parameters:
-
body(bytes | BinaryIO | StreamInterface, default:b'') –The payload. Bytes are held in memory; an open binary file object is taken over as it is; a stream that is already one comes straight back, since wrapping it again would only add a cursor over a cursor.
Returns:
-
StreamInterface–The stream.
detach ¶
get_size ¶
Return the size of the stream in bytes, when that is knowable.
The size is measured by seeking to the end and back, so it is always current; it is then remembered until the next write.
Returns:
tell ¶
Return where the cursor currently sits.
Returns:
-
int–The cursor's offset in bytes from the beginning of the stream.
Raises:
-
StreamError–When the stream is detached, or the position cannot be read.
eof ¶
Tell whether reading has reached the end of the stream.
It reports that a read found the end, not merely that the cursor sits there: a stream just written to is at its end but has not reached it. A seek puts that back to not-yet.
A read coming back with less than was asked for is not in itself the end either — a pipe or a socket answers with whatever has arrived — unless the cursor can be asked, and has reached the size.
Returns:
is_seekable ¶
Tell whether the cursor can be moved.
Returns:
-
bool–Truewhen the file object seeks and the stream still holds it.
seek
async
¶
Move the cursor to a position in the stream.
Parameters:
-
offset(int) –How far to move, in bytes.
-
whence(int, default:SEEK_SET) –What
offsetcounts from:os.SEEK_SET,os.SEEK_CURoros.SEEK_END.
Raises:
-
StreamError–When the stream is detached, is not seekable, or the cursor cannot be moved there.
rewind
async
¶
Move the cursor back to the beginning of the stream.
Raises:
-
StreamError–When the stream is detached or not seekable.
is_writable ¶
write
async
¶
Write bytes at the cursor.
Parameters:
-
data(bytes) –What to write.
Returns:
-
int–How many bytes were written.
Raises:
-
StreamError–When the stream is detached, is not writable, or the write fails.
is_readable ¶
read
async
¶
Read up to length bytes from the cursor.
Parameters:
-
length(int) –The most to read.
Returns:
-
bytes–What was read, or empty bytes at the end of the stream.
Raises:
-
StreamError–When the stream is detached, is not readable, or the read fails.
get_contents
async
¶
Read the whole of the stream, from the first byte to the last.
Rewinds first when the cursor can be moved, then reads to the end. A
stream that cannot be rewound has nothing to rewind to, so that one is
read from wherever its cursor sits; :meth:read is the way to take a
measured amount from the current position instead.
Returns:
-
bytes–Every byte in the stream.
Raises:
-
StreamError–When the stream is detached, cannot be rewound after saying it can, or cannot be read. An unreadable body is reported rather than answered with empty bytes, which would be indistinguishable from an empty one.
get_metadata ¶
Return what the stream knows about itself.
Three entries: mode, how the file object was opened; seekable,
whether its cursor moves; and uri, the path it was opened on when
it has one.
Parameters:
-
key(str | None, default:None) –One entry to look up.
Noneasks for all of them.
Returns:
UploadedFile ¶
UploadedFile(stream_or_file: StreamInterface | str | BinaryIO, size: int | None, error: int, client_filename: str | None = None, client_media_type: str | None = None)
Bases: UploadedFileInterface
One uploaded file: what arrived, how much of it, and from where.
Two kinds arrive. One is already a stream — a form parser handed it over — and comes back as that same stream. The other is a path on disk, which is opened only when the file is read, so that a request carrying twenty files nobody looks at opens none of them.
import asyncio
from xtr_http_message import Stream, UploadedFile
upload = UploadedFile(Stream.create(b"hello"), 5, 0, "greeting.txt", "text/plain")
assert asyncio.run(upload.get_stream().get_contents()) == b"hello"
An upload that did not go through carries nothing: the error says why, and reading or moving it is refused. Moving it is what consumes it, so a second move is refused too.
Record an uploaded file.
Parameters:
-
stream_or_file(StreamInterface | str | BinaryIO) –What arrived: a stream over the contents, a path on disk, or an open binary file object. Ignored when
errorsays the upload did not go through. -
size(int | None) –The size in bytes as the file arrived, or
Nonewhen it was not counted. -
error(int) –How the upload went, as one of :class:
~xtr_http_message_contracts.upload_error.UploadError. -
client_filename(str | None, default:None) –The file name the client sent, if any. Do not trust it.
-
client_media_type(str | None, default:None) –The media type the client sent, if any. Do not trust that either.
Raises:
-
InvalidArgumentError–When
erroris not one of the upload outcomes, or when the upload went through with nothing to read it from.
get_stream ¶
Return the contents of the file as a stream.
A file backed by a path is opened here, every time it is asked for; a file that arrived as a stream comes back as that same stream.
Returns:
-
StreamInterface–The contents of the uploaded file.
Raises:
-
UploadedFileError–When the upload did not go through, when the file has already been moved, or when the path it is on cannot be opened.
move_to
async
¶
Move the file to target_path, consuming it.
A file on disk is moved as it is. One that arrived as a stream is copied a mebibyte at a time, so that a large upload never has to fit in memory.
Parameters:
-
target_path(str) –Where to move the file to, absolute or relative.
Raises:
-
InvalidArgumentError–When the target path is empty.
-
UploadedFileError–When the upload did not go through, when the file has already been moved, or when the move fails.
get_size ¶
get_error ¶
get_client_filename ¶
Uri ¶
Bases: UriInterface
A URI, taken apart into its components and put back together as text.
Build one from a string and read any component off it; change one and get a new instance, since a URI is a value rather than a thing with a state:
from xtr_http_message import Uri
uri = Uri("https://example.com/orders?page=2")
assert uri.get_host() == "example.com"
assert str(uri.with_path("/orders/7")) == "https://example.com/orders/7?page=2"
Components arrive encoded or not, as the caller has them, and come back
encoded exactly once. The standard port of the scheme is dropped, since it
says nothing the scheme does not: Uri("https://example.com:443") has
no port to report.
A string is read as RFC 3986 defines a URI reference: a scheme opens with a
letter (§3.1), a host is an IPv6 address in brackets — a grammar with no
room for a zone identifier — or a registered name of unreserved
characters, per cent escapes and sub-delimiters (§3.2.2), and a port is
digits inside sixteen bits, written after a host (§3.2.3 and §3.2). A
string that breaks one of those — http://exa mple.com,
http://[::1, http://[fe80::1%eth0], http://h:65536, //:80
— is refused, as is an http or https URI naming an authority with
no host in it, such as http:// (RFC 9110 §4.2.1 and §4.2.2). Nothing
is trimmed and no character is dropped: whatever a path, a query string or
a fragment may not carry as it is comes back per cent-encoded.
Being read is not the same as being a URI reference. A string whose front
is no scheme — ht tp://h/, 0:0 — is read as a path and comes back
per cent-encoded, and the result may still be no URI reference: §4.2
leaves a colon out of the first segment of a relative-path one, so
0:0 would read as a scheme to somebody resolving it. Put ./ in
front of such a path, or give the reference a scheme.
Read a URI out of a string, as RFC 3986 defines one.
Parameters:
-
uri(str, default:'') –The URI. Empty — the default — builds one with no component at all, to be assembled through the
with_*methods.
Raises:
-
InvalidArgumentError–When the string cannot be read as a URI reference — a host or a port that is not one, a port with no host to belong to, or no host under a scheme that needs one.
get_scheme ¶
Return the scheme, lowercased, without its trailing colon.
Returns:
-
str–The scheme, or an empty string when the URI has none.
get_authority ¶
get_user_info ¶
Return the user information as username[:password].
Returns:
-
str–The user information, or an empty string when the URI has none.
get_host ¶
get_port ¶
get_path ¶
Return the path, percent-encoded.
Two corrections are applied, so that the path read off a URI is one
that can be used as it is: a rootless path gains a leading / when
there is an authority to keep it apart from, and a path opening with
more than one / has those reduced to one.
Returns:
-
str–The path.
get_query ¶
Return the query string, percent-encoded, without its leading ?.
Returns:
-
str–The query string, or an empty string when the URI has none.
get_fragment ¶
Return the fragment, percent-encoded, without its leading #.
Returns:
-
str–The fragment, or an empty string when the URI has none.
with_scheme ¶
Return an instance carrying scheme.
A port that was non-standard for the old scheme may be standard for the new one, so the port is weighed again.
Parameters:
-
scheme(str) –The scheme the new instance carries, in any case. Empty removes the scheme.
Returns:
-
Self–A new instance, or this one when the scheme is already that.
with_user_info ¶
Return an instance carrying user and, optionally, password.
Parameters:
-
user(str) –The user name. Empty with no password removes the user information; empty with a password keeps the password under a user name that is empty, which is what
:passsays. -
password(str | None, default:None) –The password that goes with
user, when there is one.
Returns:
with_host ¶
Return an instance carrying host.
Parameters:
-
host(str) –The host, in any case. Empty removes the host.
Returns:
-
Self–A new instance, or this one when the host is already that.
Raises:
-
InvalidArgumentError–When the host is not one as RFC 3986 §3.2.2 writes it. That grammar is ASCII throughout, so a name in another script is given in its
xn--form — and aHostheader is written straight off this component, which is the other reason nothing else may reach it.
with_port ¶
Return an instance carrying port.
Parameters:
-
port(int | None) –The port, or
Noneto remove it. The standard port of the current scheme is taken asNone.
Returns:
-
Self–A new instance, or this one when the port is already that.
Raises:
-
InvalidArgumentError–When the port falls outside the range a TCP or UDP port is assigned from.