Skip to content

xtr_http_message_contracts

The HTTP message contract: what code that handles requests depends on, and nothing more.

A library that reads a request or fills in a response should not decide which class is one. It takes a :class:ServerRequestInterface and a :class:ResponseInterface, or the factory that makes them, and leaves the choice of implementation to the application — so two libraries written against this contract pass messages to each other without either knowing what the other installed.

What is here is only what appears in that contract:

  • :class:MessageInterface — the protocol version, headers and body every message has.
  • :class:RequestInterface / :class:ServerRequestInterface — a request going out, and one that arrived with everything the server learned alongside it.
  • :class:ResponseInterface — a status code, a reason phrase, and a message.
  • :class:StreamInterface — the body, as a cursor over bytes.
  • :class:UriInterface — a URI taken apart into its components.
  • :class:UploadedFileInterface and :class:UploadError — a file that came in with a request, and how its upload went.
  • The six factories, also under xtr_http_message_contracts.factory, for building any of the above without naming a class.

Every message is immutable: a with_* method leaves the instance it was called on alone and returns one carrying the change.

A body moves bytes, so reading and writing one is awaited.

from xtr_http_message_contracts import ResponseInterface, ServerRequestInterface


async def whoami(request: ServerRequestInterface, response: ResponseInterface) -> ResponseInterface:
    _ = await response.get_body().write(request.get_header_line("user-agent").encode())
    return response.with_header("content-type", "text/plain")

An implementation builds on these types rather than redefining them, so a container can register one under an interface and a library that never imported it receives it. Bridging a message to the web framework an application runs on belongs with that framework's integration, not here.

RequestFactoryInterface

Bases: Protocol

Makes a request, so that a caller need not name the class that is one.

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, the factory builds the URI from it.

Returns:

ResponseFactoryInterface

Bases: Protocol

Makes a response, so that a caller need not name the class that is one.

create_response

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

Return a new response carrying code and reason_phrase.

Parameters:

  • code (int, default: 200 ) –

    The status code; 200 unless another is asked for.

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

    The phrase to go with code in the response. None — nothing given — lets the factory fill in the phrase recommended for the code; "" asks for a response with no phrase at all. Those are two different requests, and only this tells them apart.

Returns:

ServerRequestFactoryInterface

Bases: Protocol

Makes a server request, so that a caller need not name the class that is one.

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 parsed or processed, and in particular neither the method nor the URI is read out of them, 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, the factory builds the URI from it.

  • server_params (Mapping[str, object] | None, default: None ) –

    The environment parameters to seed the request with. None seeds it with none.

Returns:

StreamFactoryInterface

Bases: Protocol

Makes a stream, so that a caller need not name the class that is one.

create_stream

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

Return a new stream holding content.

The stream should be backed by something temporary rather than by a file the caller has to clean up.

Parameters:

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

    The bytes the stream starts out holding.

Returns:

create_stream_from_file

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

Return a new stream reading a file that already exists.

The file is opened in mode, which may be any mode the host's file opener accepts, and filename may be anything it can open.

Parameters:

  • filename (str) –

    The file, or the address of the stream, to read.

  • mode (str, default: 'r' ) –

    How to open it.

Returns:

Raises:

create_stream_from_resource

create_stream_from_resource(resource: BinaryIO) -> StreamInterface

Return a new stream around a file object that is already open.

The stream must be readable, and may be writable.

Parameters:

  • resource (BinaryIO) –

    The open file object to wrap.

Returns:

UploadedFileFactoryInterface

Bases: Protocol

Makes an uploaded file, so that a caller need not name the class that is one.

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.

Given no size, the factory works it out from the stream itself.

Parameters:

  • stream (StreamInterface) –

    The contents of the uploaded file.

  • size (int | None, default: None ) –

    The size in bytes, when it is already known.

  • error (int, default: OK ) –

    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.

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

    The media type the client sent, if any.

Returns:

Raises:

UriFactoryInterface

Bases: Protocol

Makes a URI, so that a caller need not name the class that is one.

create_uri

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

Return a new URI parsed from uri.

Parameters:

  • uri (str, default: '' ) –

    The URI as text; empty for a URI with no components at all.

Returns:

Raises:

  • ValueError –

    When the text cannot be parsed as a URI.

MessageInterface

Bases: Protocol

An HTTP message: a protocol version, headers and a body.

Requests travel from a client to a server and responses back the other way; everything they share is here.

Messages are immutable. Every with_* method keeps the instance it was called on as it was and returns one carrying the change, so a message handed around cannot be altered behind the back of whoever handed it on.

get_protocol_version

get_protocol_version() -> str

Return the HTTP version of the message.

Returns:

  • str –

    The version number alone, such as "1.1" or "1.0" — never

  • str –

    the protocol name with it.

with_protocol_version

with_protocol_version(version: str) -> Self

Return an instance carrying version.

Parameters:

  • version (str) –

    The HTTP version number alone, such as "1.1".

Returns:

  • Self –

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

get_headers

get_headers() -> Mapping[str, Sequence[str]]

Return every header, each name mapped to all of its values.

A name comes back in the case it was first given in, even though names are matched without regard to case elsewhere, so a message can be written out the way it arrived:

for name, values in message.get_headers().items():
    print(f"{name}: {', '.join(values)}")

Returns:

has_header

has_header(name: str) -> bool

Tell whether a header is present, matching name without case.

Parameters:

  • name (str) –

    The header name, in any case.

Returns:

  • bool –

    True when some header name matches name ignoring case;

  • bool –

    False when none does.

get_header

get_header(name: str) -> Sequence[str]

Return every value recorded under a header, matched without case.

Parameters:

  • name (str) –

    The header name, in any case.

Returns:

  • Sequence[str] –

    All the values under that header, in order. A header the message

  • Sequence[str] –

    does not carry gives an empty sequence.

get_header_line

get_header_line(name: str) -> str

Return the values of a header joined with commas, matched without case.

Not every header can be written this way; where comma-joining would change the meaning, read :meth:get_header and join the values with whatever separator that header calls for.

Parameters:

  • name (str) –

    The header name, in any case.

Returns:

  • str –

    The values joined with commas. A header the message does not

  • str –

    carry gives an empty string.

with_header

with_header(name: str, value: str | Sequence[str]) -> Self

Return an instance whose name header holds value and nothing else.

Whatever was recorded under that header is replaced. The case of name is kept and is what :meth:get_headers reports, even though the header it replaces is found without regard to case.

Parameters:

  • name (str) –

    The header name, in any case.

  • value (str | Sequence[str]) –

    One value, or every value the header is to hold.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the name or a value is not a valid header name or value.

with_added_header

with_added_header(name: str, value: str | Sequence[str]) -> Self

Return an instance with value appended to the name header.

What the header already held stays; the new values go after it. A header the message did not carry is added.

Parameters:

  • name (str) –

    The header name, in any case.

  • value (str | Sequence[str]) –

    One value, or every value to append.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the name or a value is not a valid header name or value.

without_header

without_header(name: str) -> Self

Return an instance with the name header gone.

The header to drop is found without regard to case.

Parameters:

  • name (str) –

    The header name, in any case.

Returns:

  • Self –

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

get_body

get_body() -> StreamInterface

Return the body of the message.

Returns:

with_body

with_body(body: StreamInterface) -> Self

Return an instance carrying body.

Parameters:

  • body (StreamInterface) –

    The stream the new instance reads its body from.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the body cannot be used as one.

RequestInterface

Bases: MessageInterface, Protocol

An outgoing, client-side request.

On top of what every message carries — a protocol version, headers and a body — a request carries a method and a URI.

A request being built must take its Host header from the URI it is given whenever no Host header was given with it.

Requests are immutable. Every with_* method keeps the instance it was called on as it was and returns one carrying the change.

get_request_target

get_request_target() -> str

Return the request-target of the message.

That is the target as it will go out for a client, as it came in for a server, or exactly as :meth:with_request_target set it.

Usually it is the origin-form of the URI the request carries — the path with the query string after it — unless something else was set explicitly.

Returns:

  • str –

    The request-target, or "/" when there is no URI to build one

  • str –

    from and none was set.

with_request_target

with_request_target(request_target: str) -> Self

Return an instance carrying request_target exactly as given.

Use it where the origin-form will not do: an absolute-form target, an authority-form one, or the asterisk-form.

Parameters:

  • request_target (str) –

    The request-target, taken verbatim.

Returns:

  • Self –

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

get_method

get_method() -> str

Return the HTTP method of the request.

Returns:

  • str –

    The method, in the case it was given in.

with_method

with_method(method: str) -> Self

Return an instance carrying method.

Methods are written in capitals by convention but compared with regard to case, so what is given should be kept as it is rather than recased.

Parameters:

  • method (str) –

    The method, case-sensitive.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the method is not a valid HTTP method.

get_uri

get_uri() -> UriInterface

Return the URI the request is for.

Returns:

with_uri

with_uri(uri: UriInterface, preserve_host: bool = False) -> Self

Return an instance carrying uri.

By default the Host header of the new instance follows the URI: it is set from the URI's host component when the URI has one, and a Host header already present carries over untouched when it has none.

Passing preserve_host=True asks instead that an existing Host header be kept, which plays out in three ways:

  • no Host header, or an empty one, and a URI with a host: the Host header of the new instance is set from the URI;
  • no Host header, or an empty one, and a URI without a host: the new instance gets no Host header either;
  • a Host header that is present and not empty: it is left exactly as it is.

Parameters:

  • uri (UriInterface) –

    The URI the new instance is for.

  • preserve_host (bool, default: False ) –

    Whether to keep the Host header the request already carries.

Returns:

  • Self –

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

ResponseInterface

Bases: MessageInterface, Protocol

An outgoing, server-side response.

On top of what every message carries — a protocol version, headers and a body — a response carries a status code and the reason phrase that goes with it.

Responses are immutable. Every with_* method keeps the instance it was called on as it was and returns one carrying the change.

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.

with_status

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

Return an instance carrying code and, optionally, reason_phrase.

Given no reason phrase, an implementation may fill in the one recommended for that code — by the HTTP specification, or by the registry of status codes kept alongside it.

Parameters:

  • code (int) –

    The three-digit status code to set.

  • reason_phrase (str, default: '' ) –

    The phrase to go with code. Left out, the implementation may choose the recommended one.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the status code is not a valid one.

get_reason_phrase

get_reason_phrase() -> str

Return the reason phrase that goes with the status code.

A status line need not carry a reason phrase at all, so there may be none to report; an implementation may answer with the phrase recommended for the code instead — by the HTTP specification, or by the registry of status codes kept alongside it.

Returns:

  • str –

    The reason phrase, or an empty string when there is none.

ServerRequestInterface

Bases: RequestInterface, Protocol

An incoming, server-side request.

On top of what every request carries — a protocol version, a method, a URI, headers and a body — this one gathers everything that reached the application with it:

  • the parameters of the environment it arrived in;
  • the cookies the client sent;
  • the query string, parsed;
  • the files that came with it, if any;
  • the body, parsed into parameters.

The environment parameters are the state the request arrived in and nothing may change them, which is why there is no method to. The rest can all be rebuilt from the environment or from the body — a body may need parsing differently once its content type is known, for one — so each of those does have a method.

A request is also worth annotating as it is handled: a path matched into named parameters, a cookie decrypted, an authorization header resolved to a user. Those findings go in the attributes.

Requests are immutable. Every with_* method keeps the instance it was called on as it was and returns one carrying the change. A request built over a connection materialises its body side lazily, and its sync getters answer what materialisation has yielded so far.

get_server_params

get_server_params() -> Mapping[str, object]

Return the parameters of the environment the request arrived in.

Where they came from is nobody's business but the implementation's: they need not describe a server process at all.

Returns:

get_cookie_params() -> Mapping[str, str]

Return the cookies the client sent.

Returns:

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

Return an instance carrying cookies.

The cookies need not be the ones that arrived; they are usually supplied when the request is built.

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.

These may have drifted from the URI and from the environment parameters, since nothing keeps the three in step. To be sure of reading what arrived, parse get_uri().get_query(), or the query string among the environment parameters, instead.

Returns:

with_query_params

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

Return an instance carrying query.

The parameters should not change over the course of the request. They may be supplied when the request is built, or derived from something else such as the URI — and where they are parsed out of the URI, how a repeated name and how a nested name come out must match what :meth:get_query_params promises.

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.

The files are arranged in a tree that follows the names of the fields they were submitted under, every leaf of it an :class:~xtr_http_message_contracts.uploaded_file_interface.UploadedFileInterface.

They may have been gathered from the environment or from the body when the request was built, or supplied through :meth:with_uploaded_files.

Returns:

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; this one is left as it was.

Raises:

  • ValueError –

    When the tree is not shaped that way.

get_parsed_body

get_parsed_body() -> object | None

Return the parameters found in the body of the request.

A POST whose content type is form-encoded or a multipart form must answer with the submitted form fields. A request built over a connection answers them once its body has been read, or once it was handed over with its body already materialised.

Anything else may answer with whatever parsing the body yielded. Parsing yields structure, so what comes back is a mapping or an object — never a scalar.

Returns:

  • object | None –

    The parsed body parameters, or None when the request has no

  • object | None –

    body to parse.

with_parsed_body

with_parsed_body(data: object | None) -> Self

Return an instance carrying data as its body parameters.

The parameters may be supplied when the request is built. Where the content type is form-encoded or a multipart form and the method is POST, this method is for the submitted form fields and nothing else.

The data need not have come from a form, but it must be what parsing the body yielded. Parsing yields structure, so only a mapping or an object is accepted — or None when there was nothing to parse.

A request whose content was negotiated to be a JSON payload, for instance, can be given the deserialised payload this way.

Parameters:

  • data (object | None) –

    The parsed body parameters, or None.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the data is of a kind that cannot be body parameters.

get_attributes

get_attributes() -> Mapping[str, object]

Return what was derived from the request while handling it.

Anything at all: the named parameters a path matched, the plaintext of a cookie, the result of parsing a body that was not a form. They belong to the application and to the request, and may change over its course.

Returns:

get_attribute

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

Return one of the attributes :meth:get_attributes describes.

Being able to name what an absent attribute should read as is why there is no method for asking whether one is there.

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 of the attributes :meth:get_attributes describes.

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; this one is left as it was.

StreamInterface

Bases: Protocol

A data stream, usually wrapping an open file object.

This is the body of every message: a cursor over bytes, with the questions worth asking before moving it — is it seekable, is it readable, is it writable.

Moving the cursor is awaited. :meth:read, :meth:write, :meth:get_contents, :meth:seek, :meth:rewind and :meth:close do input and output, so a body can be fed by a socket as readily as by a file, without blocking whoever is waiting on it. The questions above only report what the stream already holds, so they cost no await.

Unlike the messages that carry it, a stream is not immutable: reading, writing and seeking all move the cursor in place.

close async

close() -> None

Close the stream and release whatever it was holding open.

detach

detach() -> BinaryIO | None

Hand the underlying file object out and leave the stream unusable.

Once detached, nothing else on this stream can be relied on; the caller owns what came back.

Returns:

  • BinaryIO | None –

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

  • BinaryIO | None –

    none.

get_size

get_size() -> int | None

Return the size of the stream in bytes, when that is known.

Returns:

  • int | None –

    The size in bytes, or None when the stream cannot say.

tell

tell() -> int

Return where the cursor currently sits.

Returns:

  • int –

    The cursor's offset in bytes from the beginning of the stream.

Raises:

eof

eof() -> bool

Tell whether the cursor has reached the end of the stream.

Returns:

  • bool –

    True once the end has been reached.

is_seekable

is_seekable() -> bool

Tell whether the cursor can be moved.

Returns:

  • bool –

    True when :meth:seek and :meth:rewind work on this stream.

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 makes it an absolute position, os.SEEK_CUR adds it to where the cursor is, os.SEEK_END adds it to the end of the stream.

Raises:

rewind async

rewind() -> None

Move the cursor back to the beginning of the stream.

Equivalent to await seek(0) on a seekable stream.

Raises:

  • RuntimeError –

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

is_writable

is_writable() -> bool

Tell whether data can be written to the stream.

Returns:

  • bool –

    True when :meth:write works on this stream.

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:

is_readable

is_readable() -> bool

Tell whether data can be read from the stream.

Returns:

  • bool –

    True when :meth:read and :meth:get_contents work on this

  • bool –

    stream.

read async

read(length: int) -> bytes

Read up to length bytes from the cursor.

Fewer than length bytes may come back, whenever the underlying file object returns fewer.

Parameters:

  • length (int) –

    The most to read.

Returns:

  • bytes –

    What was read, or empty bytes when nothing was available.

Raises:

get_contents async

get_contents() -> bytes

Read the whole of the stream, from the first byte to the last.

Rewinds first when the stream is seekable, then reads to the end. On a stream that cannot be rewound there is nothing to rewind to, so this reads from wherever the cursor sits; :meth:read is the way to take a measured amount from the current position instead.

Beware: this may pull a very large amount of data into memory.

Returns:

  • bytes –

    Every byte in the stream.

Raises:

  • RuntimeError –

    When the stream cannot be read, or reading fails part way. 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.

The keys are those of the underlying file object — mode, seekable and uri among them.

Parameters:

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

    One entry to look up. None asks for all of them.

Returns:

  • object –

    A mapping of every entry when key is None; otherwise the

  • object –

    value under key, or None when the stream carries no such

  • object –

    entry.

UploadError

Bases: IntEnum

The outcome an uploaded file reports from :meth:get_error.

The standard this package translates describes the outcome as one of a set of numbered constants its host language defines. Nothing here defines them, so they are gathered into this enumeration, keeping the numbers the wire and the standard already agree on — which is why 5 is missing: that number was never assigned.

Being an :class:~enum.IntEnum, a member compares and passes as the integer the contract calls for, so an implementation may hold either.

OK class-attribute instance-attribute

OK = 0

The file arrived whole; nothing went wrong.

INI_SIZE class-attribute instance-attribute

INI_SIZE = 1

The file was larger than the limit the server configuration allows.

FORM_SIZE class-attribute instance-attribute

FORM_SIZE = 2

The file was larger than the limit the submitted form itself named.

PARTIAL class-attribute instance-attribute

PARTIAL = 3

The upload stopped part way; only some of the file arrived.

NO_FILE class-attribute instance-attribute

NO_FILE = 4

The field was submitted with no file in it.

NO_TMP_DIR class-attribute instance-attribute

NO_TMP_DIR = 6

There was nowhere to put the incoming file while it was being received.

CANT_WRITE class-attribute instance-attribute

CANT_WRITE = 7

The incoming file could not be written to where it was being kept.

EXTENSION class-attribute instance-attribute

EXTENSION = 8

Something the server had loaded refused the upload.

UploadedFileInterface

Bases: Protocol

One uploaded file, as a value: what arrived, how much of it, and from where.

Instances are immutable — nothing here returns a changed copy, and nothing changes the file in place except :meth:move_to, which is the one operation that consumes it and, because it does input and output, the one that is awaited.

get_stream

get_stream() -> StreamInterface

Return the contents of the file as a stream.

Reading it as a stream is what lets the file be copied anywhere a stream can be written to.

Returns:

Raises:

  • RuntimeError –

    When there is no stream to be had — :meth:move_to having already taken the file away, among other reasons.

move_to async

move_to(target_path: str) -> None

Move the file to target_path, consuming it.

The path may be absolute or relative; a relative one is resolved the way the file system calls of the host resolve one.

Whatever held the file is gone once the move completes, which is why calling it a second time is an error rather than a second move.

To put the file somewhere a path cannot name, read :meth:get_stream and write that where it needs to go.

Parameters:

  • target_path (str) –

    Where to move the file to.

Raises:

  • ValueError –

    When the target path is not a usable one.

  • RuntimeError –

    When the move fails, or when the file has already been moved.

get_size

get_size() -> int | None

Return the size of the file in bytes.

The size reported should be the one recorded as the file arrived, counted from what was actually received.

Returns:

  • int | None –

    The size in bytes, or None when it is not known.

get_error

get_error() -> int

Return how the upload went.

The value is one of :class:~xtr_http_message_contracts.upload_error.UploadError, and it is :attr:~xtr_http_message_contracts.upload_error.UploadError.OK when the file arrived whole. The value recorded as the file arrived is the one that should come back.

Returns:

  • int –

    The outcome of the upload.

get_client_filename

get_client_filename() -> str | None

Return the file name the client sent.

Do not trust it. It is whatever the client chose to send, and a client may well have chosen it to break something.

The name recorded as the file arrived is the one that should come back.

Returns:

  • str | None –

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

get_client_media_type

get_client_media_type() -> str | None

Return the media type the client sent.

Do not trust it either, and for the same reason.

The media type recorded as the file arrived is the one that should come back.

Returns:

  • str | None –

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

UriInterface

Bases: Protocol

A URI as a value: every component readable, every change a new instance.

Its first use is the target of a request, but nothing here is bound to that — any URI fits. A request usually carries the host in a Host header as well, and a server-side request usually finds the scheme among its server parameters.

Instances are immutable. Every with_* method keeps the instance it was called on as it was and returns one carrying the change.

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].

The port is left out when it is not set, and should be left out when it is the standard port of the current scheme.

Returns:

  • str –

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

get_user_info

get_user_info() -> str

Return the user information as username[:password].

The password is appended after a colon only when there is one. The trailing @ belongs to the authority, not here, and is never added.

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.

A port that is non-standard for the current scheme comes back as an integer. The standard port of the current scheme should come back as None, since it adds nothing.

With no port and no scheme, the answer is always None. With no port but a scheme, an implementation may answer with that scheme's standard port, though None is the better answer.

Returns:

  • int | None –

    The port, or None.

get_path

get_path() -> str

Return the path, percent-encoded.

A path may be empty, absolute (opening with a slash), or rootless (not opening with a slash); all three are supported.

The empty path and "/" are elsewhere treated as the same thing, but this method must not normalise one into the other: where a base path has been trimmed off, the difference matters, and telling the two apart is the caller's job.

Characters that have to be encoded are encoded, and never encoded twice. A slash meant as data rather than as a segment separator must therefore reach the instance already written as %2F.

Returns:

  • str –

    The path.

get_query

get_query() -> str

Return the query string, percent-encoded, without its leading ?.

Characters that have to be encoded are encoded, and never encoded twice. An ampersand meant as data rather than as a separator must therefore reach the instance already written as %26.

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 #.

Characters that have to be encoded are encoded, and never encoded twice.

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.

http and https are supported whatever their case; other schemes may be. An empty scheme removes the scheme.

Parameters:

  • scheme (str) –

    The scheme the new instance carries.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the scheme is malformed or unsupported.

with_user_info

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

Return an instance carrying user and, optionally, password.

A password without a user cannot be expressed: an empty user removes the user information entirely.

Parameters:

  • user (str) –

    The user name of the authority.

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

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

Returns:

  • Self –

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

with_host

with_host(host: str) -> Self

Return an instance carrying host.

An empty host removes the host.

Parameters:

  • host (str) –

    The host the new instance carries.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the host is not a valid host name.

with_port

with_port(port: int | None) -> Self

Return an instance carrying port.

None removes the port.

Parameters:

  • port (int | None) –

    The port the new instance carries, or None.

Returns:

  • Self –

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

Raises:

  • ValueError –

    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.

A path may be empty, absolute (opening with a slash), or rootless (not opening with a slash); all three are supported. A path meant to be relative to the host rather than to a base path has to open with a slash, since one that does not is taken as relative to a base path the application knows about.

Characters may be given encoded or not; the instance sees to the encoding :meth:get_path describes.

Parameters:

  • path (str) –

    The path the new instance carries.

Returns:

  • Self –

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

Raises:

with_query

with_query(query: str) -> Self

Return an instance carrying query.

Characters may be given encoded or not; the instance sees to the encoding :meth:get_query describes. An empty query string removes the query string.

Parameters:

  • query (str) –

    The query string the new instance carries.

Returns:

  • Self –

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

Raises:

  • ValueError –

    When the query string is malformed.

with_fragment

with_fragment(fragment: str) -> Self

Return an instance carrying fragment.

Characters may be given encoded or not; the instance sees to the encoding :meth:get_fragment describes. An empty fragment removes the fragment.

Parameters:

  • fragment (str) –

    The fragment the new instance carries.

Returns:

  • Self –

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