datastructures

class litestar.datastructures.URL[原始碼]

基底類別:object

Representation and modification utilities of a URL.

fragment: str

Fragment component.

hostname: str | None

Hostname if specified.

netloc: str

Network location.

password: str | None

Password if specified.

path: str

Hierarchical path.

port: int | None

Port if specified.

query: str

Query string.

scheme: str

URL scheme.

username: str | None

Username if specified.

static __new__(cls, url: str | SplitResult) URL[原始碼]

Create a new instance.

參數:

url -- url string or split result to represent.

classmethod from_components(scheme: str = '', netloc: str = '', path: str = '', fragment: str = '', query: str = '') Self[原始碼]

Create a new URL from components.

參數:
  • scheme -- URL 方案

  • netloc -- 網路位置

  • path -- Hierarchical path

  • query -- Query component

  • fragment -- Fragment identifier

回傳:

A new URL with the given components

classmethod from_scope(scope: Scope) Self[原始碼]

Construct a URL from a Scope

參數:

scope -- A scope

回傳:

A URL

property query_params: MultiDict

Query parameters of a URL as a MultiDict

回傳:

A MultiDict with query parameters

備註

  • The returned MultiDict is mutable, URL itself is immutable,

    therefore mutating the query parameters will not directly mutate the URL. If you want to modify query parameters, make modifications in the multidict and pass them back to with_replacements()

with_replacements(scheme: str = '', netloc: str = '', path: str = '', query: str | MultiDict | None | EmptyType = _EmptyEnum.EMPTY, fragment: str = '') Self[原始碼]

Create a new URL, replacing the given components.

參數:
  • scheme -- URL 方案

  • netloc -- 網路位置

  • path -- Hierarchical path

  • query -- Raw query string

  • fragment -- Fragment identifier

回傳:

A new URL with the given components replaced

class litestar.datastructures.Accept[原始碼]

基底類別:object

An Accept header.

__init__(accept_value: str) None[原始碼]
accepts(media_type: str) bool[原始碼]

Check if the request accepts the specified media type.

If multiple media types can be provided, it is better to use best_match().

參數:

media_type -- The media type to check for.

回傳:

True if the request accepts media_type.

best_match(provided_types: list[str], default: str | None = None) str | None[原始碼]

Find the best matching media type for the request.

參數:
  • provided_types -- A list of media types that can be provided as a response. These types can contain a wildcard * character in the main- or subtype part.

  • default -- The media type that is returned if none of the provided types match.

回傳:

The best matching media type. If the matching provided type contains wildcard characters, they are replaced with the corresponding part of the accepted type. Otherwise the provided type is returned as-is.

class litestar.datastructures.Address[原始碼]

基底類別:NamedTuple

Just a network address.

static __new__(_cls, host: str, port: int)

Create new instance of Address(host, port)

host: str

Address host.

port: int

Address port.

class litestar.datastructures.CacheControlHeader[原始碼]

基底類別:Header

A cache-control header.

__init__(documentation_only: bool = False, max_age: int | None = None, s_maxage: int | None = None, no_cache: bool | None = None, no_store: bool | None = None, private: bool | None = None, public: bool | None = None, no_transform: bool | None = None, must_revalidate: bool | None = None, proxy_revalidate: bool | None = None, must_understand: bool | None = None, immutable: bool | None = None, stale_while_revalidate: int | None = None) None
classmethod from_header(header_value: str) CacheControlHeader[原始碼]

Create a CacheControlHeader instance from the header value.

參數:

header_value -- the header value as string

回傳:

An instance of CacheControlHeader

immutable: bool | None = None

Accessor for the immutable directive.

max_age: int | None = None

Accessor for the max-age directive.

must_revalidate: bool | None = None

Accessor for the must-revalidate directive.

must_understand: bool | None = None

Accessor for the must-understand directive.

no_cache: bool | None = None

Accessor for the no-cache directive.

no_store: bool | None = None

Accessor for the no-store directive.

no_transform: bool | None = None

Accessor for the no-transform directive.

classmethod prevent_storing() CacheControlHeader[原始碼]

Create a cache-control header with the no-store directive which indicates that any caches of any kind (private or shared) should not store this response.

private: bool | None = None

Accessor for the private directive.

proxy_revalidate: bool | None = None

Accessor for the proxy-revalidate directive.

public: bool | None = None

Accessor for the public directive.

s_maxage: int | None = None

Accessor for the s-maxage directive.

stale_while_revalidate: int | None = None

Accessor for the stale-while-revalidate directive.

class litestar.datastructures.Cookie[原始碼]

基底類別:object

Container class for defining a cookie using the Set-Cookie header.

See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for more details regarding this header.

__eq__(other: Any) bool[原始碼]

Determine whether two cookie instances are equal according to the cookie spec, i.e. hey have a similar path, domain and key.

參數:

other -- An arbitrary value

回傳:

A boolean

__init__(key: str, path: str = '/', value: str | None = None, max_age: int | None = None, expires: int | None = None, domain: str | None = None, secure: bool | None = None, httponly: bool | None = None, samesite: Literal['lax', 'strict', 'none'] = 'lax', description: str | None = None, documentation_only: bool = False) None
description: str | None = None

Description of the response cookie header for OpenAPI documentation.

property dict: dict[str, Any]

Get the cookie as a dict.

回傳:

A dict of values

documentation_only: bool = False

Defines the Cookie instance as for OpenAPI documentation purpose only.

domain: str | None = None

Domain for which the cookie is valid.

expires: int | None = None

Seconds from now until the cookie expires.

httponly: bool | None = None

Forbids javascript to access the cookie via document.cookie.

max_age: int | None = None

Maximal age of the cookie before its invalidated.

path: str = '/'

Path fragment that must exist in the request url for the cookie to be valid.

預設值為 /

samesite: Literal['lax', 'strict', 'none'] = 'lax'

Controls whether or not a cookie is sent with cross-site requests.

Defaults to 'lax'.

secure: bool | None = None

Https is required for the cookie.

Get a simple cookie object from the values.

回傳:

A SimpleCookie

to_encoded_header() tuple[bytes, bytes][原始碼]

Create encoded header for ASGI send.

回傳:

A two tuple of bytes.

to_header(**kwargs: Any) str[原始碼]

Return a string representation suitable to be sent as HTTP headers.

參數:

**kwargs -- Any kwargs to pass to the simple cookie output method.

value: str | None = None

Value for the cookie, if none given defaults to empty string.

key: str

Key for the cookie.

class litestar.datastructures.ETag[原始碼]

基底類別:Header

An etag header.

__init__(documentation_only: bool = False, weak: bool = False, value: str | None = None) None
classmethod from_header(header_value: str) ETag[原始碼]

Construct an etag header from its string representation.

Note that this will unquote etag-values

class litestar.datastructures.FormMultiDict[原始碼]

基底類別:ImmutableMultiDict[Any]

MultiDict for form data.

async close() None[原始碼]

Close all files in the multi-dict.

回傳:

None

classmethod from_form_data(form_data: dict[str, list[str] | str | UploadFile]) FormMultiDict[原始碼]

Create a FormMultiDict from form data.

參數:

form_data -- Form data to create the FormMultiDict from.

回傳:

A FormMultiDict instance

class litestar.datastructures.Header[原始碼]

基底類別:ABC

An abstract type for HTTP headers.

__init__(documentation_only: bool = False) None
documentation_only: bool = False

Defines the header instance as for OpenAPI documentation purpose only.

abstractmethod classmethod from_header(header_value: str) Header[原始碼]

Construct a header from its string representation.

to_header(include_header_name: bool = False) str[原始碼]

Get the header as string.

參數:

include_header_name -- should include the header name in the return value. If set to false the return value will only include the header value. if set to true the return value will be: <header name>: <header value>. Defaults to false.

class litestar.datastructures.Headers[原始碼]

基底類別:CIMultiDictProxy[str], MultiMixin[str]

An immutable, case-insensitive multi dict for HTTP headers.

__init__(headers: Mapping[str, str] | RawHeaders | MultiDict[str] | None = None) None[原始碼]

初始化 Headers

參數:

headers -- 初始值。

classmethod from_scope(scope: Scope) Headers[原始碼]

Create headers from a send-message.

參數:

scope -- The ASGI connection scope.

回傳:

Headers

引發:

ValueError -- If the message does not have a headers key

to_header_list() RawHeadersList[原始碼]

Raw header value.

回傳:

A list of tuples contain the header and header-value as bytes

class litestar.datastructures.ImmutableMultiDict[原始碼]

基底類別:MultiDictProxy[T], MultiMixin[T], Generic[T]

Immutable MultiDict, using class:MultiDictProxy <multidict.MultiDictProxy>.

__init__(args: MultiMapping | Mapping[str, Any] | Iterable[tuple[str, Any]] | None = None) None[原始碼]

Initialize ImmutableMultiDict from a MultiMapping`, Mapping or an iterable of tuples.

參數:

args -- Mapping-like structure to create the ImmutableMultiDict from

copy() Self[原始碼]

Return a shallow copy

mutable_copy() MultiDict[T][原始碼]

Create a mutable copy as a MultiDict

回傳:

A mutable multi dict

class litestar.datastructures.ImmutableState[原始碼]

基底類別:Mapping[str, Any]

An object meant to store arbitrary state.

It can be accessed using dot notation while exposing dict like functionalities.

__bool__() bool[原始碼]

Return a boolean indicating whether the wrapped dict instance has values.

__copy__() Self[原始碼]

Return a shallow copy of the given state object.

Customizes how the builtin "copy" function will work.

classmethod __get_validators__() Generator[Callable[[ImmutableState | dict[str, Any] | Iterable[tuple[str, Any]]], ImmutableState], None, None][原始碼]

Pydantic compatible method to allow custom parsing of state instances in a SignatureModel.

__getattr__(key: str) Any[原始碼]

Get the value for the corresponding key from the wrapped state object using attribute notation.

參數:

key -- Key to retrieve

引發:

AttributeError -- if the given attribute is not set.

回傳:

The retrieved value

__getitem__(key: str) Any[原始碼]

Get the value for the corresponding key from the wrapped state object using subscription notation.

參數:

key -- Key to access.

引發:

KeyError --

回傳:

A value from the wrapped state instance.

__init__(state: ImmutableState | Mapping[str, Any] | Iterable[tuple[str, Any]], deep_copy: bool = True) None[原始碼]

Initialize an ImmutableState instance.

參數:
  • state -- An object to initialize the state from. Can be a dict, an instance of ImmutableState, or a tuple of key value paris.

  • deep_copy -- Whether to 'deepcopy' the passed in state.

範例

from litestar.datastructures import ImmutableState

state_dict = {"first": 1, "second": 2, "third": 3, "fourth": 4}
state = ImmutableState(state_dict)

# state implements the Mapping type:
assert len(state) == 3
assert "first" in state
assert not "fourth" in state
assert state["first"] == 1
assert [(k, v) for k, v in state.items()] == [("first", 1), ("second", 2), ("third", 3)]

# state implements __bool__
assert state  # state is true when it has values.
assert not State()  # state is empty when it has no values.

# it has a 'dict' method to retrieve a shallow copy of the underlying dict
inner_dict = state.dict()
assert inner_dict == state_dict

# you can also retrieve a mutable State by calling 'mutable_copy'
mutable_state = state.mutable_copy()
del state["first"]
assert "first" not in state
__iter__() Iterator[str][原始碼]

Return an iterator iterating the wrapped state dict.

回傳:

An iterator of strings

__len__() int[原始碼]

Return length of the wrapped state dict.

回傳:

An integer

dict() dict[str, Any][原始碼]

Return a shallow copy of the wrapped dict.

回傳:

A dict

mutable_copy() State[原始碼]

Return a mutable copy of the state object.

回傳:

A State

classmethod validate(value: ImmutableState | dict[str, Any] | Iterable[tuple[str, Any]]) Self[原始碼]

Parse a value and instantiate state inside a SignatureModel. This allows us to use custom subclasses of state, as well as allows users to decide whether state is mutable or immutable.

參數:

value -- The value from which to initialize the state instance.

回傳:

An ImmutableState instance

class litestar.datastructures.MultiDict[原始碼]

基底類別:MultiDict[T], MultiMixin[T], Generic[T]

MultiDict, using MultiDict.

__init__(args: MultiMapping | Mapping[str, T] | Iterable[tuple[str, T]] | None = None) None[原始碼]

Initialize MultiDict from a`MultiMapping``, Mapping or an iterable of tuples.

參數:

args -- Mapping-like structure to create the MultiDict from

copy() Self[原始碼]

Return a shallow copy

immutable() ImmutableMultiDict[T][原始碼]

Create an.

ImmutableMultiDict view.

回傳:

An immutable multi dict

class litestar.datastructures.MultiMixin[原始碼]

基底類別:Generic[T], MultiMapping[T], ABC

Mixin providing common methods for multi dicts, used by ImmutableMultiDict and MultiDict

dict() dict[str, list[Any]][原始碼]

Return the multi-dict as a dict of lists.

回傳:

A dict of lists

multi_items() Generator[tuple[str, T], None, None][原始碼]

Get all keys and values, including duplicates.

回傳:

A list of tuples containing key-value pairs

class litestar.datastructures.MutableScopeHeaders[原始碼]

基底類別:MutableMapping

A case-insensitive, multidict-like structure that can be used to mutate headers within a Scope

__delitem__(key: str) None[原始碼]

Delete all headers matching name

__getitem__(key: str) str[原始碼]

Get the first header matching name

__init__(scope: HeaderScope | None = None) None[原始碼]

Initialize MutableScopeHeaders from a HeaderScope.

參數:

scope -- The ASGI connection scope.

__iter__() Iterator[str][原始碼]

Create an iterator of header names including duplicates.

__len__() int[原始碼]

Return the length of the internally stored headers, including duplicates.

__setitem__(key: str, value: str) None[原始碼]

Set a header in the scope, overwriting duplicates.

add(key: str, value: str) None[原始碼]

Add a header to the scope.

備註

  • This method keeps duplicates.

參數:
  • key -- Header key.

  • value -- Header value.

回傳:

None.

extend_header_value(key: str, value: str) None[原始碼]

Extend a multivalued header.

備註

  • A multivalues header is a header that can take a comma separated list.

  • If the header previously did not exist, it will be added.

參數:
  • key -- Header key.

  • value -- Header value to add,

回傳:

None

classmethod from_message(message: Message) MutableScopeHeaders[原始碼]

Construct a header from a message object.

參數:

message -- Message

回傳:

MutableScopeHeaders。

引發:

ValueError -- If the message does not have a headers key.

getall(key: str, default: list[str] | None = None) list[str][原始碼]

Get all values of a header.

參數:
  • key -- Header key.

  • default -- Default value to return if name is not found.

回傳:

A list of strings.

引發:

KeyError -- if no header for name was found and default is not given.

class litestar.datastructures.ResponseHeader[原始碼]

基底類別:object

Container type for a response header.

__init__(name: str, documentation_only: bool = False, value: str | None = None, description: str | None = None, required: bool = False, deprecated: bool = False, style: str | None = None, explode: bool | None = None, example: Any | None = None, examples: dict[str, Example] | None = None) None
__post_init__() None[原始碼]

Ensure that either value is set or the instance is for documentation_only.

deprecated: bool = False

Specifies that a parameter is deprecated and SHOULD be transitioned out of usage.

Default value is false.

description: str | None = None

A brief description of the parameter. This could contain examples of use.

[CommonMark syntax](https://spec.commonmark.org/) MAY be used for rich text representation.

documentation_only: bool = False

Defines the ResponseHeader instance as for OpenAPI documentation purpose only.

example: Any | None = None

Example of the parameter's potential value.

The example SHOULD match the specified schema and encoding properties if present. The example field is mutually exclusive of the examples field. Furthermore, if referencing a schema that contains an example, the example value SHALL _override_ the example provided by the schema. To represent examples of media types that cannot naturally be represented in JSON or YAML, a string value can contain the example with escaping where necessary.

examples: dict[str, Example] | None = None

Examples of the parameter's potential value. Each example SHOULD contain a value in the correct format as specified in the parameter encoding. The examples field is mutually exclusive of the example field. Furthermore, if referencing a schema that contains an example, the examples value SHALL _override_ the example provided by the schema.

For more complex scenarios, the [content](https://spec.openapis.org/oas/v3.1.0#parameterContent) property can define the media type and schema of the parameter. A parameter MUST contain either a schema property, or a content property, but not both. When example or examples are provided in conjunction with the schema object, the example MUST follow the prescribed serialization strategy for the parameter.

explode: bool | None = None

When this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map.

For other types of parameters this property has no effect. When [style](https://spec.openapis.org/oas/v3.1.0#parameterStyle) is form, the default value is true. For all other styles, the default value is false.

required: bool = False

Determines whether this parameter is mandatory.

If the [parameter location](https://spec.openapis.org/oas/v3.1.0#parameterIn) is "path", this property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default value is false.

style: str | None = None

Describes how the parameter value will be serialized depending on the type of the parameter value. Default values (based on value of in):

  • for query - form;

  • for path - simple;

  • for header - simple;

  • for cookie - form.

value: str | None = None

Value to set for the response header.

name: str

Header name

class litestar.datastructures.SecretBytes[原始碼]

基底類別:SecretValue[bytes]

Represents a secret bytes value.

get_obscured() bytes[原始碼]

Overrides the base class method to return the hidden bytes value.

回傳:

The hidden bytes representation of the secret value.

回傳型別:

bytes

class litestar.datastructures.SecretString[原始碼]

基底類別:SecretValue[str]

Represents a secret string value.

get_obscured() str[原始碼]

Overrides the base class method to return the hidden string value.

回傳:

The hidden string representation of the secret value.

回傳型別:

str

class litestar.datastructures.State[原始碼]

基底類別:ImmutableState, MutableMapping[str, Any]

An object meant to store arbitrary state.

It can be accessed using dot notation while exposing dict like functionalities.

__delattr__(key: str) None[原始碼]

Delete the value from the key from the wrapped state object using attribute notation.

參數:

key -- Key to delete

引發:

AttributeError -- if the given attribute is not set.

回傳:

None

__delitem__(key: str) None[原始碼]

Delete the value from the key from the wrapped state object using subscription notation.

參數:

key -- Key to delete

引發:

KeyError -- if the given attribute is not set.

回傳:

None

__init__(state: ImmutableState | Mapping[str, Any] | Iterable[tuple[str, Any]] | None = None, deep_copy: bool = False) None[原始碼]

Initialize a State instance with an optional value.

參數:
  • state -- An object to initialize the state from. Can be a dict, an instance of 'ImmutableState', or a tuple of key value paris.

  • deep_copy -- Whether to 'deepcopy' the passed in state.

範例
from litestar.datastructures import State

state_dict = {"first": 1, "second": 2, "third": 3, "fourth": 4}
state = State(state_dict)

# state can be accessed using '.' notation
assert state.fourth == 4
del state.fourth

# state implements the Mapping type:
assert len(state) == 3
assert "first" in state
assert not "fourth" in state
assert state["first"] == 1
assert [(k, v) for k, v in state.items()] == [("first", 1), ("second", 2), ("third", 3)]

state["fourth"] = 4
assert "fourth" in state
del state["fourth"]

# state implements __bool__
assert state  # state is true when it has values.
assert not State()  # state is empty when it has no values.

# it has shallow copy
copied_state = state.copy()
del copied_state.first
assert state.first

# it has a 'dict' method to retrieve a shallow copy of the underlying dict
inner_dict = state.dict()
assert inner_dict == state_dict

# you can get an immutable copy of the state by calling 'immutable_immutable_copy'
immutable_copy = state.immutable_copy()
del immutable_copy.first  #  raises AttributeError
__setattr__(key: str, value: Any) None[原始碼]

Set an item in the state using attribute notation.

參數:
  • key -- Key to set.

  • value -- Value to set.

回傳:

None

__setitem__(key: str, value: Any) None[原始碼]

Set an item in the state using subscription notation.

參數:
  • key -- Key to set.

  • value -- Value to set.

回傳:

None

copy() Self[原始碼]

Return a shallow copy of the state object.

回傳:

A State

immutable_copy() ImmutableState[原始碼]

Return a shallow copy of the state object, setting it to be frozen.

回傳:

A State

class litestar.datastructures.UploadFile[原始碼]

基底類別:object

Representation of a file upload

__init__(content_type: str, filename: str, file_data: bytes | None = None, headers: dict[str, str] | None = None, max_spool_size: int = 1048576) None[原始碼]

Upload file in-memory container.

參數:
  • content_type -- Content type for the file.

  • filename -- The filename.

  • file_data -- File data.

  • headers -- Any attached headers.

  • max_spool_size -- The size above which the temporary file will be rolled to disk.

async close() None[原始碼]

Async proxy for file close.

回傳:

None.

async read(size: int = -1) bytes[原始碼]

Proxy for data reading.

參數:

size -- position from which to read.

回傳:

Byte string.

property rolled_to_disk: bool

Determine whether the spooled file exceeded the rolled-to-disk threshold and is no longer in memory.

回傳:

A boolean flag

async seek(offset: int) int[原始碼]

Async proxy for file seek.

參數:

offset -- start position..

回傳:

The new absolute file position (in bytes) after seeking.

async write(data: bytes | bytearray) int[原始碼]

Proxy for data writing.

參數:

data -- Byte string to write.

回傳:

Number of bytes written (int).