Skip to content

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 the Host header 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

create_request(method: str, uri: UriInterface | str) -> RequestInterface

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:

create_response

create_response(code: int = 200, reason_phrase: str | None = None) -> ResponseInterface

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:

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. None seeds it with none.

Returns:

create_stream

create_stream(content: bytes = b'') -> StreamInterface

Return a new stream over content, held in memory.

Parameters:

  • content (bytes, default: b'' ) –

    The bytes the stream reads back.

Returns:

create_stream_from_file

create_stream_from_file(filename: str, mode: str = 'r') -> StreamInterface

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:

Raises:

create_stream_from_resource

create_stream_from_resource(resource: BinaryIO) -> StreamInterface

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:

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:

Raises:

create_uri

create_uri(uri: str = '') -> UriInterface

Return a new URI read from uri.

Parameters:

  • uri (str, default: '' ) –

    The URI as text. Empty builds one with no component at all.

Returns:

Raises:

LazyStream

LazyStream(materialise: Callable[[], Awaitable[bytes]])

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:

materialised property

materialised: bool

Tell whether the body has been read into memory.

close async

close() -> None

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

detach() -> BinaryIO | None

Hand out the buffer's file object, or None while there is none.

get_size

get_size() -> int | None

Return the size of the buffered body, or None before there is one.

tell

tell() -> int

Return where the cursor sits: the first byte, until there is a buffer.

eof

eof() -> bool

Tell whether a read reached the end: no read has, until there is a buffer.

is_seekable

is_seekable() -> bool

Tell whether the cursor moves: the buffer it will be is over bytes in memory.

seek async

seek(offset: int, whence: int = os.SEEK_SET) -> None

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

rewind() -> None

Move the cursor back to the first byte, materialising if nothing has read.

is_writable

is_writable() -> bool

Tell whether bytes can be written to the buffer: it is a buffer, so yes.

write async

write(data: bytes) -> int

Write at the cursor, materialising the body if nothing has read it yet.

Raises:

  • StreamError –

    When the buffer cannot be written to.

is_readable

is_readable() -> bool

Tell whether bytes can be read: they can, once anything has been read.

read async

read(length: int) -> bytes

Read up to length bytes, materialising the body if nothing has read it yet.

Raises:

get_contents async

get_contents() -> bytes

Return every byte of the body, materialising it if nothing has read it yet.

Raises:

get_metadata

get_metadata(key: str | None = None) -> object

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:

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

materialise() -> bytes

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

parsed_body() -> object | None

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

uploaded_files() -> Mapping[str, object]

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

attributes() -> Mapping[str, object]

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 for status; an empty string leaves the response with none.

Raises:

get_status_code

get_status_code() -> int

Return the status code of the response.

Returns:

  • int –

    The three-digit code saying how the server got on with the

  • int –

    request.

get_reason_phrase

get_reason_phrase() -> str

Return the reason phrase that goes with the status code.

Returns:

  • str –

    The reason phrase, or an empty string when the response carries

  • str –

    none.

with_status

with_status(code: int, reason_phrase: str = '') -> Self

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 for code is filled in where there is one.

Returns:

  • Self –

    A new instance; this one is left as it was.

Raises:

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. None means none.

Raises:

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:

get_server_params

get_server_params() -> Mapping[str, object]

Return the parameters of the environment the request arrived in.

Returns:

get_cookie_params() -> Mapping[str, str]

Return the cookies the client sent.

Returns:

  • Mapping[str, str] –

    Each cookie name mapped to its value — the mapping as it was given

  • Mapping[str, str] –

    where nothing can change it, otherwise a fresh one.

with_cookie_params(cookies: Mapping[str, str]) -> Self

Return an instance carrying cookies.

Neither the Cookie header of the new instance nor its environment parameters change with them.

Parameters:

  • cookies (Mapping[str, str]) –

    Each cookie name mapped to its value.

Returns:

  • Self –

    A new instance; this one is left as it was.

get_query_params

get_query_params() -> Mapping[str, object]

Return the query string, parsed into parameters.

Returns:

with_query_params

with_query_params(query: Mapping[str, object]) -> Self

Return an instance carrying query.

Neither the URI the request holds nor its environment parameters change with them.

Parameters:

Returns:

  • Self –

    A new instance; this one is left as it was.

get_uploaded_files

get_uploaded_files() -> Mapping[str, object]

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

with_uploaded_files(uploaded_files: Mapping[str, object]) -> Self

Return an instance carrying uploaded_files.

Parameters:

  • uploaded_files (Mapping[str, object]) –

    A tree of uploaded files, shaped as :meth:get_uploaded_files describes.

Returns:

  • Self –

    A new instance answering uploaded_files from now on, however

  • Self –

    late the body of the connection it was copied from is read; this

  • Self –

    one is left as it was.

get_parsed_body

get_parsed_body() -> object | None

Return the parameters found in the body of the request.

Returns:

  • object | None –

    Whatever parsing the body yielded, or None when 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 –

    None until 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

with_parsed_body(data: object | None) -> Self

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 None when there was nothing to parse.

Returns:

  • Self –

    A new instance answering data from 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

get_attributes() -> Mapping[str, object]

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

get_attribute(name: str, default: object | None = None) -> object | None

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, or default.

with_attribute

with_attribute(name: str, value: object) -> Self

Return an instance carrying one more attribute.

Parameters:

  • name (str) –

    The attribute name.

  • value (object) –

    The value to record under it.

Returns:

  • Self –

    A new instance; this one is left as it was.

without_attribute

without_attribute(name: str) -> Self

Return an instance with the name attribute gone.

Parameters:

  • name (str) –

    The attribute name.

Returns:

  • Self –

    A new instance, or this one when the request carries no such

  • Self –

    attribute. A connected request always answers a copy: its

  • Self –

    attributes are live, so the name is looked for in what they

  • Self –

    answer now, and the copy detaches either way.

Stream

Stream(body: BinaryIO)

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

create(body: bytes | BinaryIO | StreamInterface = b'') -> StreamInterface

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:

close async

close() -> None

Close the file object and let go of it.

detach

detach() -> BinaryIO | None

Hand the file object out and leave the stream unusable.

Returns:

  • BinaryIO | None –

    The file object the stream wrapped, or None when it has

  • BinaryIO | None –

    already been handed out.

get_size

get_size() -> int | None

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:

  • int | None –

    The size in bytes, or None when the stream is detached or

  • int | None –

    cannot be seeked over.

tell

tell() -> int

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

eof() -> bool

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:

  • bool –

    True once a read has reached the end, and for a detached

  • bool –

    stream.

is_seekable

is_seekable() -> bool

Tell whether the cursor can be moved.

Returns:

  • bool –

    True when the file object seeks and the stream still holds it.

seek async

seek(offset: int, whence: int = os.SEEK_SET) -> None

Move the cursor to a position in the stream.

Parameters:

  • offset (int) –

    How far to move, in bytes.

  • whence (int, default: SEEK_SET ) –

    What offset counts from: os.SEEK_SET, os.SEEK_CUR or os.SEEK_END.

Raises:

  • StreamError –

    When the stream is detached, is not seekable, or the cursor cannot be moved there.

rewind async

rewind() -> None

Move the cursor back to the beginning of the stream.

Raises:

  • StreamError –

    When the stream is detached or not seekable.

is_writable

is_writable() -> bool

Tell whether data can be written to the stream.

Returns:

  • bool –

    True when the file object accepts writes and the stream still

  • bool –

    holds it.

write async

write(data: bytes) -> int

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

is_readable() -> bool

Tell whether data can be read from the stream.

Returns:

  • bool –

    True when the file object serves reads and the stream still

  • bool –

    holds it.

read async

read(length: int) -> bytes

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

get_contents() -> bytes

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

get_metadata(key: str | None = None) -> object

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. None asks for all of them.

Returns:

  • object –

    A fresh mapping of every entry when key is None, empty for

  • object –

    a detached stream; otherwise the value under key, or None

  • object –

    when there is no such entry.

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 error says the upload did not go through.

  • size (int | None) –

    The size in bytes as the file arrived, or None when 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 error is not one of the upload outcomes, or when the upload went through with nothing to read it from.

get_stream

get_stream() -> StreamInterface

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:

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_to(target_path: str) -> None

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:

get_size

get_size() -> int | None

Return the size of the file in bytes.

Returns:

  • int | None –

    The size recorded as the file arrived, or None when it was not

  • int | None –

    counted.

get_error

get_error() -> int

Return how the upload went.

Returns:

  • int –

    The outcome, which is

  • int –

    attr:~xtr_http_message_contracts.upload_error.UploadError.OK

  • int –

    when the file arrived whole.

get_client_filename

get_client_filename() -> str | None

Return the file name the client sent.

Returns:

  • str | None –

    The name the client sent, or None when it sent none. Do not

  • str | None –

    trust it: a client may well have chosen it to break something.

get_client_media_type

get_client_media_type() -> str | None

Return the media type the client sent.

Returns:

  • str | None –

    The media type the client sent, or None when it sent none. Do

  • str | None –

    not trust it either, and for the same reason.

Uri

Uri(uri: str = '')

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

get_scheme() -> str

Return the scheme, lowercased, without its trailing colon.

Returns:

  • str –

    The scheme, or an empty string when the URI has none.

get_authority

get_authority() -> str

Return the authority as [user-info@]host[:port].

Returns:

  • str –

    The authority, or an empty string when the URI has no host — user

  • str –

    information without a host cannot be written down.

get_user_info

get_user_info() -> str

Return the user information as username[:password].

Returns:

  • str –

    The user information, or an empty string when the URI has none.

get_host

get_host() -> str

Return the host, lowercased.

Returns:

  • str –

    The host, or an empty string when the URI has none.

get_port

get_port() -> int | None

Return the port, when one is worth reporting.

Returns:

  • int | None –

    The port when it is not the standard one of the scheme, otherwise

  • int | None –

    None.

get_path

get_path() -> str

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

get_query() -> str

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

get_fragment() -> str

Return the fragment, percent-encoded, without its leading #.

Returns:

  • str –

    The fragment, or an empty string when the URI has none.

with_scheme

with_scheme(scheme: str) -> Self

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

with_user_info(user: str, password: str | None = None) -> Self

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 :pass says.

  • password (str | None, default: None ) –

    The password that goes with user, when there is one.

Returns:

  • Self –

    A new instance, or this one when the user information is already

  • Self –

    that.

with_host

with_host(host: str) -> Self

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 a Host header is written straight off this component, which is the other reason nothing else may reach it.

with_port

with_port(port: int | None) -> Self

Return an instance carrying port.

Parameters:

  • port (int | None) –

    The port, or None to remove it. The standard port of the current scheme is taken as None.

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.

with_path

with_path(path: str) -> Self

Return an instance carrying path.

Parameters:

  • path (str) –

    The path, encoded or not. It may be empty, absolute, or rootless.

Returns:

  • Self –

    A new instance, or this one when the path is already that.

with_query

with_query(query: str) -> Self

Return an instance carrying query.

Parameters:

  • query (str) –

    The query string, encoded or not, without a leading ? unless that question mark is data. Empty removes it.

Returns:

  • Self –

    A new instance, or this one when the query string is already that.

with_fragment

with_fragment(fragment: str) -> Self

Return an instance carrying fragment.

Parameters:

  • fragment (str) –

    The fragment, encoded or not, without a leading # unless that hash is data. Empty removes it.

Returns:

  • Self –

    A new instance, or this one when the fragment is already that.