sanic.headers.AcceptList#

A list of media types, as used in the Accept header.

Inherits from: list

class AcceptList(iterable = ())

The Accept header entries are listed in order of preference, starting with the most preferred. This class is a list of MediaType objects, that encapsulate also the q value or any other parameters.

Two separate methods are provided for searching the list:

  • 'match' for finding the most preferred match (wildcards supported)
  • operator 'in' for checking explicit matches (wildcards as literals)
Parameters
*args
MediaType

Any number of MediaType objects.

match#

Find a media type accepted by the client.

def match(self, mimes: str, accept_wildcards = True): -> Matched

This method can be used to find which of the media types requested by the client is most preferred against the ones given as arguments.

The ordering of preference is set by:

  1. The order set by RFC 7231, s. 5.3.2, giving a higher priority to q values and more specific type definitions,
  2. The order of the arguments (first is most preferred), and
  3. The first matching entry on the Accept header.

Wildcards are matched both ways. A match is usually found, as the Accept headers typically include */*, in particular if the header is missing, is not manually set, or if the client is a browser.

Note: the returned object behaves as a string of the mime argument that matched, and is empty/falsy if no match was found. The matched header entry MediaType or None is available as the m attribute.

Parameters
mimes
List[str]

Any MIME types to search for in order of preference.

accept_wildcards
bool

Match Accept entries with wildcards in them.

Return
Match

A match object with the mime string and the MediaType object.

sanic.headers.Matched#

A matching result of a MIME string against a header.

class Matched(mime: str, header: Optional[MediaType])

This class is a representation of a matching result of a MIME string against a header. It encapsulates the MIME string, the header, and provides methods for matching against other MIME strings.

Parameters
mime
str

The MIME string to match.

header
MediaType

The header to match against, if any.

match#

Match this MIME string against another MIME string.

def match(self, other: Union[str, Matched]): -> Optional[Matched]

Check if this MIME string matches the given MIME string. Wildcards are supported both ways on both type and subtype.

Parameters
other
str

A MIME string to match.

Return
Matched

Returns self if the MIME strings are compatible. None: Returns None if the MIME strings are not compatible.

parse#

@classmethod
def parse(raw: str): -> Matched

sanic.headers.MediaType#

A media type, as used in the Accept header.

class MediaType(type_: str, subtype: str, params: str)

This class is a representation of a media type, as used in the Accept header. It encapsulates the type, subtype and any parameters, and provides methods for matching against other media types.

Two separate methods are provided for searching the list:

  • 'match' for finding the most preferred match (wildcards supported)
  • operator 'in' for checking explicit matches (wildcards as literals)
Parameters
type_
str

The type of the media type.

subtype
str

The subtype of the media type.

**params
str

Any parameters for the media type.

has_wildcard#

Return True if this media type has a wildcard in it.

@property
def has_wildcard(self): -> bool

Return
bool

True if this media type has a wildcard in it.

match#

Match this media type against another media type.

def match(self, mime_with_params: Union[str, MediaType]): -> Optional[MediaType]

Check if this media type matches the given mime type/subtype. Wildcards are supported both ways on both type and subtype. If mime contains a semicolon, optionally followed by parameters, the parameters of the two media types must match exactly.

Note

Use the == operator instead to check for literal matches without expanding wildcards.

Parameters
media_type
str

A type/subtype string to match.

Return
MediaType

Returns self if the media types are compatible. None: Returns None if the media types are not compatible.

sanic.headers.format_http1_response#

Format a HTTP/1.1 response header.

def format_http1_response(status: int, headers: HeaderBytesIterable): -> bytes

Parameters
status
int

The HTTP status code.

headers
HeaderBytesIterable

An iterable of header tuples.

Return
bytes

The formatted response header.

sanic.headers.fwd_normalize#

Normalize and convert values extracted from forwarded headers.

def fwd_normalize(fwd: OptionsIterable): -> Options

Parameters
fwd
OptionsIterable

An iterable of key-value pairs.

Return
Options

A dict of normalized key-value pairs.

sanic.headers.fwd_normalize_address#

Normalize address fields of proxy headers.

def fwd_normalize_address(addr: str): -> str

Parameters
addr
str

An address string.

Return
str

A normalized address string.

sanic.headers.parse_accept#

Parse an Accept header and order the acceptable media types according to RFC 7231, s. 5.3.2

def parse_accept(accept: Optional[str]): -> AcceptList

https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2

Parameters
accept
str

The Accept header value to parse.

Return
AcceptList

A list of MediaType objects, ordered by preference.

Raises
InvalidHeader

If the header value is invalid.

sanic.headers.parse_content_header#

Parse content-type and content-disposition header values.

def parse_content_header(value: str): -> Tuple[str, Options]

E.g. form-data; name=upload; filename="file.txt" to ('form-data', {'name': 'upload', 'filename': 'file.txt'})

Mostly identical to cgi.parse_header and werkzeug.parse_options_header
but runs faster and handles special characters better.

Unescapes %22 to `"` and %0D%0A to `

` in field values.

Args:
    value (str): The header value to parse.

Returns:
    Tuple[str, Options]: The header value and a dict of options.

sanic.headers.parse_credentials#

Parses any header with the aim to retrieve any credentials from it.

def parse_credentials(header: Optional[str], prefixes: Optional[Union[List, Tuple, Set]] = None): -> Tuple[Optional[str], Optional[str]]

Parameters
header
Optional[str]

The header to parse.

prefixes
Optional[Union[List, Tuple, Set]]

The prefixes to look for. Defaults to None.

Return
Tuple[Optional[str], Optional[str]]

The prefix and the credentials.

sanic.headers.parse_forwarded#

Parse RFC 7239 Forwarded headers.

def parse_forwarded(headers, config): -> Optional[Options]

The value of by or secret must match config.FORWARDED_SECRET

sanic.headers.parse_host#

Split host:port into hostname and port.

def parse_host(host: str): -> Tuple[Optional[str], Optional[int]]

Parameters
host
str

A host string.

Return
Tuple[Optional[str], Optional[int]]

A tuple of hostname and port.

sanic.headers.parse_xforwarded#

Parse traditional proxy headers.

def parse_xforwarded(headers, config): -> Optional[Options]