Warning

These documents are OUTDATED as of 2023-12-31.

Please refer to the latest version of the documentation at sanic.dev.

Core

sanic.cookies

class sanic.cookies.Cookie(key, value, *, path='/', domain=None, secure=True, max_age=None, expires=None, httponly=False, samesite='Lax', partitioned=False, comment=None, host_prefix=False, secure_prefix=False)

Bases: dict

A representation of a HTTP cookie, providing an interface to manipulate cookie attributes intended for a response.

This class is a simplified representation of a cookie, similar to the Morsel SimpleCookie in Python’s standard library. It allows the manipulation of various cookie attributes including path, domain, security settings, and others.

Several β€œsmart defaults” are provided to make it easier to create cookies that are secure by default. These include:

  • Setting the secure flag to True by default

  • Setting the samesite flag to Lax by default

Args:

key (str): The key (name) of the cookie. value (str): The value of the cookie. path (str, optional): The path for the cookie. Defaults to β€œ/”. domain (Optional[str], optional): The domain for the cookie.

Defaults to None.

secure (bool, optional): Whether the cookie is secure.

Defaults to True.

max_age (Optional[int], optional): The maximum age of the cookie

in seconds. Defaults to None.

expires (Optional[datetime], optional): The expiration date of the

cookie. Defaults to None.

httponly (bool, optional): HttpOnly flag for the cookie.

Defaults to False.

samesite (Optional[SameSite], optional): The SameSite attribute for

the cookie. Defaults to β€œLax”.

partitioned (bool, optional): Whether the cookie is partitioned.

Defaults to False.

comment (Optional[str], optional): A comment for the cookie.

Defaults to None.

host_prefix (bool, optional): Whether to use the host prefix.

Defaults to False.

secure_prefix (bool, optional): Whether to use the secure prefix.

Defaults to False.

Parameters:
  • key (str) –

  • value (str) –

  • path (str) –

  • domain (Optional[str]) –

  • secure (bool) –

  • max_age (Optional[int]) –

  • expires (Optional[datetime]) –

  • httponly (bool) –

  • samesite (Optional[SameSite]) –

  • partitioned (bool) –

  • comment (Optional[str]) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

encode(encoding)

Encode the cookie content in a specific type of encoding instructed by the developer.

Leverages the str.encode method provided by Python.

This method can be used to encode and embed utf-8 content into the cookies.

Warning

Direct encoding of a Cookie object has been deprecated and will be removed in v24.3.

Args:

encoding (str): The encoding type to be used.

Returns:

bytes: The encoded cookie content.

Parameters:

encoding (str) –

Return type:

bytes

classmethod make_key(key, host_prefix=False, secure_prefix=False)

Create a cookie key with the appropriate prefix.

Cookies can have one ow two prefixes. The first is __Host- which requires that the cookie be set with path=”/”, domain=None, and secure=True. The second is __Secure- which requires that secure=True.

They cannot be combined.

Args:

key (str): The key (name) of the cookie. host_prefix (bool, optional): Whether to add __Host- as a prefix to the key.

This requires that path=”/”, domain=None, and secure=True. Defaults to False.

secure_prefix (bool, optional): Whether to add __Secure- as a prefix to the key.

This requires that secure=True. Defaults to False.

Raises:

ServerError: If both host_prefix and secure_prefix are set.

Returns:

str: The key with the appropriate prefix.

Parameters:
  • key (str) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

Return type:

str

property comment: str | None

A comment for the cookie. Defaults to None.

property domain: str | None

The domain of the cookie. Defaults to None.

property expires: datetime | None

The expiration date of the cookie. Defaults to None.

property httponly: bool

Whether the cookie is HTTP only. Defaults to False.

property max_age: int | None

The maximum age of the cookie in seconds. Defaults to None.

property partitioned: bool

Whether the cookie is partitioned. Defaults to False.

property path: str

The path of the cookie. Defaults to β€œ/”.

property samesite: Literal['Strict'] | Literal['Lax'] | Literal['None'] | Literal['strict'] | Literal['lax'] | Literal['none'] | None

The SameSite attribute for the cookie. Defaults to β€œLax”.

property secure: bool

Whether the cookie is secure. Defaults to True.

class sanic.cookies.CookieJar(headers)

Bases: dict

A container to manipulate cookies.

CookieJar dynamically writes headers as cookies are added and removed It gets around the limitation of one header per name by using the MultiHeader class to provide a unique key that encodes to Set-Cookie.

Args:

headers (Header): The headers object to write cookies to.

Parameters:

headers (Header) –

Add a cookie to the CookieJar.

Args:

key (str): Key of the cookie. value (str): Value of the cookie. path (str, optional): Path of the cookie. Defaults to β€œ/”. domain (Optional[str], optional): Domain of the cookie. Defaults to None. secure (bool, optional): Whether to set it as a secure cookie. Defaults to True. max_age (Optional[int], optional): Max age of the cookie in seconds; if set to 0 a

browser should delete it. Defaults to None.

expires (Optional[datetime], optional): When the cookie expires; if set to None browsers

should set it as a session cookie. Defaults to None.

httponly (bool, optional): Whether to set it as HTTP only. Defaults to False. samesite (Optional[SameSite], optional): How to set the samesite property, should be

strict, lax, or none (case insensitive). Defaults to β€œLax”.

partitioned (bool, optional): Whether to set it as partitioned. Defaults to False. comment (Optional[str], optional): A cookie comment. Defaults to None. host_prefix (bool, optional): Whether to add __Host- as a prefix to the key.

This requires that path=”/”, domain=None, and secure=True. Defaults to False.

secure_prefix (bool, optional): Whether to add __Secure- as a prefix to the key.

This requires that secure=True. Defaults to False.

Returns:

Cookie: The instance of the created cookie.

Raises:

ServerError: If host_prefix is set without secure=True. ServerError: If host_prefix is set without path=”/” and domain=None. ServerError: If host_prefix is set with domain. ServerError: If secure_prefix is set without secure=True. ServerError: If partitioned is set without host_prefix=True.

Examples:

Basic usage `python cookie = add_cookie('name', 'value') `

Adding a cookie with a custom path and domain `python cookie = add_cookie('name', 'value', path='/custom', domain='example.com') `

Adding a secure, HTTP-only cookie with a comment `python cookie = add_cookie('name', 'value', secure=True, httponly=True, comment='My Cookie') `

Adding a cookie with a max age of 60 seconds `python cookie = add_cookie('name', 'value', max_age=60) `

Parameters:
  • key (str) –

  • value (str) –

  • path (str) –

  • domain (str | None) –

  • secure (bool) –

  • max_age (int | None) –

  • expires (datetime | None) –

  • httponly (bool) –

  • samesite (Literal['Strict'] | ~typing.Literal['Lax'] | ~typing.Literal['None'] | ~typing.Literal['strict'] | ~typing.Literal['lax'] | ~typing.Literal['none'] | None) –

  • partitioned (bool) –

  • comment (str | None) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

Return type:

Cookie

Delete a cookie

This will effectively set it as Max-Age: 0, which a browser should interpret it to mean: β€œdelete the cookie”.

Since it is a browser/client implementation, your results may vary depending upon which client is being used.

Parameters:
  • key (str) – The key to be deleted

  • path (Optional[str], optional) – Path of the cookie, defaults to None

  • domain (Optional[str], optional) – Domain of the cookie, defaults to None

  • host_prefix (bool) – Whether to add __Host- as a prefix to the key. This requires that path=”/”, domain=None, and secure=True, defaults to False

  • secure_prefix (bool) – Whether to add __Secure- as a prefix to the key. This requires that secure=True, defaults to False

Return type:

None

get(*args, **kwargs)

Deprecated in v24.3

Fetch a cookie from the CookieJar.

Args:

key (str): The key of the cookie to fetch. path (str, optional): The path of the cookie. Defaults to β€œ/”. domain (Optional[str], optional): The domain of the cookie.

Defaults to None.

host_prefix (bool, optional): Whether to add __Host- as a prefix to the key.

This requires that path=”/”, domain=None, and secure=True. Defaults to False.

secure_prefix (bool, optional): Whether to add __Secure- as a prefix to the key.

This requires that secure=True. Defaults to False.

Returns:

Optional[Cookie]: The cookie if it exists, otherwise None.

Parameters:
  • key (str) –

  • path (str) –

  • domain (str | None) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

Return type:

Cookie | None

Check if a cookie exists in the CookieJar.

Args:

key (str): The key of the cookie to check. path (str, optional): The path of the cookie. Defaults to β€œ/”. domain (Optional[str], optional): The domain of the cookie.

Defaults to None.

host_prefix (bool, optional): Whether to add __Host- as a prefix to the key.

This requires that path=”/”, domain=None, and secure=True. Defaults to False.

secure_prefix (bool, optional): Whether to add __Secure- as a prefix to the key.

This requires that secure=True. Defaults to False.

Returns:

bool: Whether the cookie exists.

Parameters:
  • key (str) –

  • path (str) –

  • domain (str | None) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

Return type:

bool

items()

Deprecated in v24.3

keys()

Deprecated in v24.3

pop(key, *args, **kwargs)

Deprecated in v24.3

values()

Deprecated in v24.3

property cookie_headers: Dict[str, str]

Deprecated in v24.3

property cookies: List[Cookie]

A list of cookies in the CookieJar.

Returns:

List[Cookie]: A list of cookies in the CookieJar.

property header_key

Deprecated in v24.3

sanic.handlers

class sanic.handlers.ContentRangeHandler(request, stats)

Bases: Range

Parse and process the incoming request headers to extract the content range information.

Args:

request (Request): The incoming request object. stats (os.stat_result): The stats of the file being served.

class sanic.handlers.DirectoryHandler(uri, directory, directory_view=False, index=None)

Bases: object

Serve files from a directory.

Args:

uri (str): The URI to serve the files at. directory (Path): The directory to serve files from. directory_view (bool): Whether to show a directory listing or not. index (Optional[Union[str, Sequence[str]]]): The index file(s) to

serve if the directory is requested. Defaults to None.

Parameters:
  • uri (str) –

  • directory (Path) –

  • directory_view (bool) –

  • index (Optional[Union[str, Sequence[str]]]) –

async handle(request, path)

Handle the request.

Args:

request (Request): The incoming request object. path (str): The path to the file to serve.

Raises:

NotFound: If the file is not found. IsADirectoryError: If the path is a directory and directory_view is False.

Returns:

Response: The response object.

Parameters:
  • request (Request) –

  • path (str) –

class sanic.handlers.ErrorHandler(base=<class 'sanic.errorpages.TextRenderer'>)

Bases: object

Process and handle all uncaught exceptions.

This error handling framework is built into the core that can be extended by the developers to perform a wide range of tasks from recording the error stats to reporting them to an external service that can be used for realtime alerting system.

Args:

base (BaseRenderer): The renderer to use for the error pages.

Parameters:

base (Type[BaseRenderer]) –

add(exception, handler, route_names=None)

Add a new exception handler to an already existing handler object.

Args:
exception (sanic.exceptions.SanicException or Exception): Type

of exception that needs to be handled.

handler (function): Reference to the function that will

handle the exception.

Returns:

None

Parameters:

route_names (List[str] | None) –

default(request, exception)

Provide a default behavior for the objects of ErrorHandler.

If a developer chooses to extend the ErrorHandler, they can provide a custom implementation for this method to behave in a way they see fit.

Args:

request (sanic.request.Request): Incoming request. exception (sanic.exceptions.SanicException or Exception): Exception object.

Returns:

HTTPResponse: The response object.

Examples:

```python class CustomErrorHandler(ErrorHandler):

def default(self, request: Request, exception: Exception) -> HTTPResponse:

# Custom logic for handling the exception and creating a response custom_response = my_custom_logic(request, exception) return custom_response

app = Sanic(β€œMyApp”, error_handler=CustomErrorHandler()) ```

Parameters:
  • request (Request) –

  • exception (Exception) –

Return type:

HTTPResponse

static log(request, exception)

Logs information about an incoming request and the associated exception.

Args:

request (Request): The incoming request to be logged. exception (Exception): The exception that occurred during the handling of the request.

Returns:

None

Parameters:
  • request (Request) –

  • exception (Exception) –

Return type:

None

lookup(exception, route_name=None)

Lookup the existing instance of ErrorHandler and fetch the registered handler for a specific type of exception.

This method leverages a dict lookup to speedup the retrieval process.

Args:
exception (sanic.exceptions.SanicException or Exception): Type

of exception.

Returns:

Registered function if found, None otherwise.

Parameters:

route_name (str | None) –

response(request, exception)

Fetch and executes an exception handler and returns a response object.

Args:

request (sanic.request.Request): Instance of the request. exception (sanic.exceptions.SanicException or Exception): Exception to handle.

Returns:

Wrap the return value obtained from the default function or the registered handler for that type of exception.

sanic.headers

class sanic.headers.AcceptList(iterable=(), /)

Bases: list

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

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)

Args:

*args (MediaType): Any number of MediaType objects.

match(*mimes, accept_wildcards=True)

Find a media type accepted by the client.

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,

  1. The order of the arguments (first is most preferred), and

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

Args:

mimes (List[str]): Any MIME types to search for in order of preference. accept_wildcards (bool): Match Accept entries with wildcards in them.

Returns:

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

Parameters:

mimes (str) –

Return type:

Matched

class sanic.headers.Matched(mime, header)

Bases: object

A matching result of a MIME string against a header.

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.

Args:

mime (str): The MIME string to match. header (MediaType): The header to match against, if any.

Parameters:
  • mime (str) –

  • header (Optional[MediaType]) –

match(other)

Match this MIME string against another MIME string.

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

Args:

other (str): A MIME string to match.

Returns:

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

Parameters:

other (str | Matched) –

Return type:

Matched | None

class sanic.headers.MediaType(type_, subtype, **params)

Bases: object

A media type, as used in the Accept header.

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)

Args:

type_ (str): The type of the media type. subtype (str): The subtype of the media type. **params (str): Any parameters for the media type.

Parameters:
  • type_ (str) –

  • subtype (str) –

  • params (str) –

match(mime_with_params)

Match this media type against another media type.

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.

Args:

media_type (str): A type/subtype string to match.

Returns:

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

Parameters:

mime_with_params (str | MediaType) –

Return type:

MediaType | None

property has_wildcard: bool

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

Returns:

bool: True if this media type has a wildcard in it.

sanic.headers.format_http1_response(status, headers)

Format a HTTP/1.1 response header.

Args:

status (int): The HTTP status code. headers (HeaderBytesIterable): An iterable of header tuples.

Returns:

bytes: The formatted response header.

Parameters:
  • status (int) –

  • headers (Iterable[Tuple[bytes, bytes]]) –

Return type:

bytes

sanic.headers.fwd_normalize(fwd)

Normalize and convert values extracted from forwarded headers.

Args:

fwd (OptionsIterable): An iterable of key-value pairs.

Returns:

Options: A dict of normalized key-value pairs.

Parameters:

fwd (Iterable[Tuple[str, str]]) –

Return type:

Dict[str, int | str]

sanic.headers.fwd_normalize_address(addr)

Normalize address fields of proxy headers.

Args:

addr (str): An address string.

Returns:

str: A normalized address string.

Parameters:

addr (str) –

Return type:

str

sanic.headers.parse_accept(accept)

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

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

Args:

accept (str): The Accept header value to parse.

Returns:

AcceptList: A list of MediaType objects, ordered by preference.

Raises:

InvalidHeader: If the header value is invalid.

Parameters:

accept (str | None) –

Return type:

AcceptList

sanic.headers.parse_content_header(value)

Parse content-type and content-disposition header values.

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.

Parameters:

value (str) –

Return type:

Tuple[str, Dict[str, int | str]]

sanic.headers.parse_credentials(header, prefixes=None)

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

Args:

header (Optional[str]): The header to parse. prefixes (Optional[Union[List, Tuple, Set]], optional): The prefixes to look for. Defaults to None.

Returns:

Tuple[Optional[str], Optional[str]]: The prefix and the credentials.

Parameters:
  • header (str | None) –

  • prefixes (List | Tuple | Set | None) –

Return type:

Tuple[str | None, str | None]

sanic.headers.parse_forwarded(headers, config)

Parse RFC 7239 Forwarded headers. The value of by or secret must match config.FORWARDED_SECRET :return: dict with keys and values, or None if nothing matched

Return type:

Dict[str, int | str] | None

sanic.headers.parse_host(host)

Split host:port into hostname and port.

Args:

host (str): A host string.

Returns:

Tuple[Optional[str], Optional[int]]: A tuple of hostname and port.

Parameters:

host (str) –

Return type:

Tuple[str | None, int | None]

sanic.headers.parse_xforwarded(headers, config)

Parse traditional proxy headers.

Return type:

Dict[str, int | str] | None

sanic.request

class sanic.request.File(type, body, name)

Bases: tuple

Model for defining a file.

It is a namedtuple, therefore you can iterate over the object, or access the parameters by name.

Args:

type (str, optional): The mimetype, defaults to β€œtext/plain”. body (bytes): Bytes of the file. name (str): The filename.

Parameters:
  • type (str) –

  • body (bytes) –

  • name (str) –

body: bytes

Alias for field number 1

name: str

Alias for field number 2

type: str

Alias for field number 0

class sanic.request.Request(url_bytes, headers, version, method, transport, app, head=b'', stream_id=0)

Bases: Generic[sanic_type, ctx_type]

State of HTTP request.

Args:

url_bytes (bytes): Raw URL bytes. headers (Header): Request headers. version (str): HTTP version. method (str): HTTP method. transport (TransportProtocol): Transport protocol. app (Sanic): Sanic instance. head (bytes, optional): Request head. Defaults to b””. stream_id (int, optional): HTTP/3 stream ID. Defaults to 0.

classmethod generate_id(*_)

Generate a unique ID for the request.

This method is called to generate a unique ID for each request. By default, it returns a uuid.UUID instance.

Returns:

Union[uuid.UUID, str, int]: A unique ID for the request.

Return type:

UUID | str | int

get_args(keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')

Parse query_string using urllib.parse.parse_qs.

This methods is used by the args property, but it also can be used directly if you need to change default parameters.

Args:
keep_blank_values (bool): Flag indicating whether blank values in

percent-encoded queries should be treated as blank strings. A True value indicates that blanks should be retained as blank strings. The default False value indicates that blank values are to be ignored and treated as if they were not included.

strict_parsing (bool): Flag indicating what to do with parsing

errors. If False (the default), errors are silently ignored. If True, errors raise a ValueError exception.

encoding (str): Specify how to decode percent-encoded sequences

into Unicode characters, as accepted by the bytes.decode() method.

errors (str): Specify how to decode percent-encoded sequences

into Unicode characters, as accepted by the bytes.decode() method.

Returns:

RequestParameters: A dictionary containing the parsed arguments.

Parameters:
  • keep_blank_values (bool) –

  • strict_parsing (bool) –

  • encoding (str) –

  • errors (str) –

Return type:

RequestParameters

classmethod get_current()

Retrieve the current request object

This implements [Context Variables](https://docs.python.org/3/library/contextvars.html) to allow for accessing the current request from anywhere.

A typical usecase is when you want to access the current request from a function that is not a handler, such as a logging function:

```python import logging

class LoggingFormater(logging.Formatter):
def format(self, record):

request = Request.get_current() record.url = request.url record.ip = request.ip return super().format(record)

```

Returns:

Request: The current request object

Raises:
sanic.exceptions.ServerError: If it is outside of a request

lifecycle.

Return type:

Request

get_form(keep_blank_values=False)

Method to extract and parse the form data from a request.

Args:

keep_blank_values (bool): Whether to discard blank values from the form data.

Returns:

Optional[RequestParameters]: The parsed form data.

Parameters:

keep_blank_values (bool) –

Return type:

RequestParameters | None

get_query_args(keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')

Parse query_string using urllib.parse.parse_qsl.

This methods is used by query_args propertyn but can be used directly if you need to change default parameters.

Args:
keep_blank_values (bool): Flag indicating whether blank values in

percent-encoded queries should be treated as blank strings. A True value indicates that blanks should be retained as blank strings. The default False value indicates that blank values are to be ignored and treated as if they were not included.

strict_parsing (bool): Flag indicating what to do with

parsing errors. If False (the default), errors are silently ignored. If True, errors raise a ValueError exception.

encoding (str): Specify how to decode percent-encoded sequences

into Unicode characters, as accepted by the bytes.decode() method.

errors (str): Specify how to decode percent-encoded sequences

into Unicode characters, as accepted by the bytes.decode() method.

Returns:

list: A list of tuples containing the parsed arguments.

Parameters:
  • keep_blank_values (bool) –

  • strict_parsing (bool) –

  • encoding (str) –

  • errors (str) –

Return type:

list

load_json(loads=None)

Load the request body as JSON

Args:

loads (Callable, optional): A custom JSON loader. Defaults to None.

Raises:

BadRequest: If the request body cannot be parsed as JSON

Returns:

Any: The request body parsed as JSON

Return type:

Any

static make_context()

Create a new context object.

This method is called when a new request context is pushed. It is a great candidate for overriding in a subclass if you want to control the type of context object that is created.

By default, it returns a types.SimpleNamespace instance.

Returns:

ctx_type: A new context object.

Return type:

ctx_type

async receive_body()

Receive request.body, if not already received.

Streaming handlers may call this to receive the full body. Sanic calls this function before running any handlers of non-streaming routes.

Custom request classes can override this for custom handling of both streaming and non-streaming routes.

reset_response()

Reset the response object.

This clears much of the state of the object. It should generally not be called directly, but is called automatically as part of the request lifecycle.

Raises:
sanic.exceptions.ServerError: If the response has already been

sent.

Return type:

None

async respond(response=None, *, status=200, headers=None, content_type=None)

Respond to the request without returning.

This method can only be called once, as you can only respond once. If no response argument is passed, one will be created from the status, headers and content_type arguments.

The first typical usecase is if you wish to respond to the request without returning from the handler:

```python @app.get(β€œ/”) async def handler(request: Request):

data = … # Process something

json_response = json({β€œdata”: data}) await request.respond(json_response)

@app.on_response async def add_header(_, response: HTTPResponse):

# Middlewares still get executed as expected response.headers[β€œone”] = β€œtwo”

```

The second possible usecase is for when you want to directly respond to the request:

```python response = await request.respond(content_type=”text/csv”) await response.send(β€œfoo,”) await response.send(β€œbar”)

# You can control the completion of the response by calling # the β€˜eof()’ method: await response.eof() ```

Args:

response (ResponseType): Response instance to send. status (int): Status code to return in the response. headers (Optional[Dict[str, str]]): Headers to return in the response, defaults to None. content_type (Optional[str]): Content-Type header of the response, defaults to None.

Returns:
FinalResponseType: Final response being sent (may be different from the

β€œresponse” parameter because of middlewares), which can be used to manually send data.

Parameters:
  • response (BaseHTTPResponse | None) –

  • status (int) –

  • headers (Header | Dict[str, str] | None) –

  • content_type (str | None) –

url_for(view_name, **kwargs)

Retrieve a URL for a given view name.

Same as sanic.Sanic.url_for, but automatically determine scheme and netloc base on the request. Since this method is aiming to generate correct schema & netloc, _external is implied.

Args:

view_name (str): The view name to generate URL for. **kwargs: Arbitrary keyword arguments to build URL query string.

Returns:

str: The generated URL.

Parameters:

view_name (str) –

Return type:

str

property accept: AcceptList

Accepted response content types.

A convenience handler for easier RFC-compliant matching of MIME types, parsed as a list that can match wildcards and includes / by default.

Returns:

AcceptList: Accepted response content types

property args: RequestParameters

Convenience property to access Request.get_args with default values.

property client_ip: str

Client IP address. 1. proxied remote address self.forwarded[β€˜for’] 2. local peer address self.ip

New in Sanic 23.6. Prefer this over remote_addr for determining the client address regardless of whether the service runs behind a proxy or not (proxy deployment needs separate configuration).

Returns:

str: IPv4, bracketed IPv6, UNIX socket name or arbitrary string

property content_type: str

Content-Type header form the request

Returns:

str: Content-Type header form the request

property cookies: RequestParameters

Incoming cookies on the request

Returns:

RequestParameters: Incoming cookies on the request

property credentials: Credentials | None

Attempt to return the auth header value.

Covers NoAuth, Basic Auth, Bearer Token, Api Token authentication schemas.

Returns:
Optional[Credentials]: A Credentials object with token, or username

and password related to the request

property ctx: ctx_type

The current request context.

This is a context object for the current request. It is created by Request.make_context and is a great place to store data that you want to be accessible during the request lifecycle.

Returns:

ctx_type: The current request context.

property endpoint: str | None

Alias of sanic.request.Request.name

Returns:

Optional[str]: The route name

property files: RequestParameters | None

The request body parsed as uploaded files

Returns:

Optional[RequestParameters]: The request body parsed as uploaded files

property form: RequestParameters | None

The request body parsed as form data

Returns:

Optional[RequestParameters]: The request body parsed as form data

property forwarded: Dict[str, int | str]

Active proxy information obtained from request headers, as specified in Sanic configuration.

Field names by, for, proto, host, port and path are normalized. - for and by IPv6 addresses are bracketed - port (int) is only set by port headers, not from host. - path is url-unencoded

Additional values may be available from new style Forwarded headers.

Returns:

Options: proxy information from request headers

property host: str

The currently effective server β€˜host’ (hostname or hostname:port).

  1. config.SERVER_NAME overrides any client headers

  2. proxied host of original request

3. request host header hostname and port may be separated by sanic.headers.parse_host(request.host).

Returns:

str: the first matching host found, or empty string

property id: UUID | str | int | None

A request ID passed from the client, or generated from the backend.

By default, this will look in a request header defined at: self.app.config.REQUEST_ID_HEADER. It defaults to X-Request-ID. Sanic will try to cast the ID into a UUID or an int.

If there is not a UUID from the client, then Sanic will try to generate an ID by calling Request.generate_id(). The default behavior is to generate a UUID. You can customize this behavior by subclassing Request and overwriting that method.

```python from sanic import Request, Sanic from itertools import count

class IntRequest(Request):

counter = count()

def generate_id(self):

return next(self.counter)

app = Sanic(β€œMyApp”, request_class=IntRequest) ```

Returns:
Optional[Union[uuid.UUID, str, int]]: A request ID passed from the

client, or generated from the backend.

property ip: str

Peer ip of the socket

Returns:

str: Peer ip of the socket

property is_cacheable: bool

Whether the HTTP method is cacheable.

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

Returns:

bool: Whether the HTTP method is cacheable.

property is_idempotent: bool

Whether the HTTP method is iempotent.

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

Returns:

bool: Whether the HTTP method is iempotent.

property is_safe: bool

Whether the HTTP method is safe.

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

Returns:

bool: Whether the HTTP method is safe.

property json: Any

The request body parsed as JSON

Returns:

Any: The request body parsed as JSON

property match_info: Dict[str, Any]

Matched path parameters after resolving route

Returns:

Dict[str, Any]: Matched path parameters after resolving route

property name: str | None

The route name

In the following pattern:

` <AppName>.[<BlueprintName>.]<HandlerName> `

Returns:

Optional[str]: The route name

property network_paths: List[Any] | None

Access the network paths if available

Returns:

Optional[List[Any]]: Access the network paths if available

property path: str

Path of the local HTTP request

Returns:

str: Path of the local HTTP request

property port: int

Peer port of the socket

Returns:

int: Peer port of the socket

property protocol: TransportProtocol

The HTTP protocol instance

Returns:

Protocol: The HTTP protocol instance

property query_args: list

Convenience property to access Request.get_query_args with default values.

property query_string: str

Representation of the requested query

Returns:

str: Representation of the requested query

property raw_headers: bytes

The unparsed HTTP headers

Returns:

bytes: The unparsed HTTP headers

property remote_addr: str

Client IP address, if available from proxy.

Returns:

str: IPv4, bracketed IPv6, UNIX socket name or arbitrary string

property request_line: bytes

The first line of a HTTP request

Returns:

bytes: The first line of a HTTP request

property scheme: str

Determine request scheme.

  1. config.SERVER_NAME if in full URL format

  2. proxied proto/scheme

  3. local connection protocol

Returns:

str: http|https|ws|wss or arbitrary value given by the headers.

property scope: MutableMapping[str, Any]

The ASGI scope of the request.

Returns:

ASGIScope: The ASGI scope of the request.

Raises:

NotImplementedError: If the app isn’t an ASGI app.

property server_name: str

hostname the client connected to, by request.host

Returns:

str: hostname the client connected to, by request.host

property server_path: str

Full path of current URL; uses proxied or local path

Returns:

str: Full path of current URL; uses proxied or local path

property server_port: int

The port the client connected to, by forwarded port or request.host.

Default port is returned as 80 and 443 based on request.scheme.

Returns:

int: The port the client connected to, by forwarded port or request.host.

property socket: Tuple[str, int] | Tuple[None, None]

Information about the connected socket if available

Returns:
Tuple[Optional[str], Optional[int]]: Information about the

connected socket if available, in the form of a tuple of (ip, port)

property stream_id: int

Access the HTTP/3 stream ID.

Raises:

sanic.exceptions.ServerError: If the request is not HTTP/3.

Returns:

int: The HTTP/3 stream ID.

property token: str | None

Attempt to return the auth header token.

Returns:

Optional[str]: The auth header token

property uri_template: str | None

The defined URI template

Returns:

Optional[str]: The defined URI template

property url: str

The URL

Returns:

str: The URL

class sanic.request.RequestParameters

Bases: dict

Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang

get(name, default=None)

Return the first value, either the default or actual

Args:

name (str): The name of the parameter default (Optional[Any], optional): The default value. Defaults to None.

Returns:

Optional[Any]: The first value of the list

Parameters:
  • name (str) –

  • default (Any | None) –

Return type:

Any | None

getlist(name, default=None)

Return the entire list

Args:

name (str): The name of the parameter default (Optional[Any], optional): The default value. Defaults to None.

Returns:

Optional[Any]: The entire list

Parameters:
  • name (str) –

  • default (Any | None) –

Return type:

Any | None

sanic.request.parse_multipart_form(body, boundary)

Parse a request body and returns fields and files

Args:

body (bytes): Bytes request body. boundary (bytes): Bytes multipart boundary.

Returns:

Tuple[RequestParameters, RequestParameters]: A tuple containing fields and files as RequestParameters.

sanic.response

class sanic.response.BaseHTTPResponse

Bases: object

The base class for all HTTP Responses

Add a cookie to the CookieJar

See [Cookies](/en/guide/basics/cookies.html)

Args:

key (str): The key to be added value (str): The value to be added path (str, optional): Path of the cookie. Defaults to β€œ/”. domain (Optional[str], optional): Domain of the cookie. Defaults to None. secure (bool, optional): Whether the cookie is secure. Defaults to True. max_age (Optional[int], optional): Max age of the cookie. Defaults to None. expires (Optional[datetime], optional): Expiry date of the cookie. Defaults to None. httponly (bool, optional): Whether the cookie is http only. Defaults to False. samesite (Optional[SameSite], optional): SameSite policy of the cookie. Defaults to β€œLax”. partitioned (bool, optional): Whether the cookie is partitioned. Defaults to False. comment (Optional[str], optional): Comment of the cookie. Defaults to None. host_prefix (bool, optional): Whether to add __Host- as a prefix to the key. This requires that path=”/”, domain=None, and secure=True. Defaults to False. secure_prefix (bool, optional): Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Returns:

Cookie: The cookie that was added

Parameters:
  • key (str) –

  • value (str) –

  • path (str) –

  • domain (str | None) –

  • secure (bool) –

  • max_age (int | None) –

  • expires (datetime | None) –

  • httponly (bool) –

  • samesite (Literal['Strict'] | ~typing.Literal['Lax'] | ~typing.Literal['None'] | ~typing.Literal['strict'] | ~typing.Literal['lax'] | ~typing.Literal['none'] | None) –

  • partitioned (bool) –

  • comment (str | None) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

Return type:

Cookie

Delete a cookie

This will effectively set it as Max-Age: 0, which a browser should interpret it to mean: β€œdelete the cookie”.

Since it is a browser/client implementation, your results may vary depending upon which client is being used.

See [Cookies](/en/guide/basics/cookies.html)

Args:

key (str): The key to be deleted path (str, optional): Path of the cookie. Defaults to β€œ/”. domain (Optional[str], optional): Domain of the cookie. Defaults to None. host_prefix (bool, optional): Whether to add __Host- as a prefix to the key. This requires that path=”/”, domain=None, and secure=True. Defaults to False. secure_prefix (bool, optional): Whether to add __Secure- as a prefix to the key. This requires that secure=True. Defaults to False.

Parameters:
  • key (str) –

  • path (str) –

  • domain (str | None) –

  • host_prefix (bool) –

  • secure_prefix (bool) –

Return type:

None

async send(data=None, end_stream=None)

Send any pending response headers and the given data as body.

Args:

data (Optional[AnyStr], optional): str or bytes to be written. Defaults to None. end_stream (Optional[bool], optional): whether to close the stream after this block. Defaults to None.

Parameters:
  • data (AnyStr | None) –

  • end_stream (bool | None) –

Return type:

None

property cookies: CookieJar

The response cookies.

See [Cookies](/en/guide/basics/cookies.html)

Returns:

CookieJar: The response cookies

property processed_headers: Iterator[Tuple[bytes, bytes]]

Obtain a list of header tuples encoded in bytes for sending.

Add and remove headers based on status and content_type.

Returns:

Iterator[Tuple[bytes, bytes]]: A list of header tuples encoded in bytes for sending

class sanic.response.HTTPResponse(body=None, status=200, headers=None, content_type=None)

Bases: BaseHTTPResponse

HTTP response to be sent back to the client.

Args:

body (Optional[Any], optional): The body content to be returned. Defaults to None. status (int, optional): HTTP response number. Defaults to 200. headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to None. content_type (Optional[str], optional): Content type to be returned (as a header). Defaults to None.

Parameters:
  • body (Optional[Any]) –

  • status (int) –

  • headers (Optional[Union[Header, Dict[str, str]]]) –

  • content_type (Optional[str]) –

async eof()

Send a EOF (End of File) message to the client.

class sanic.response.JSONResponse(body=None, status=200, headers=None, content_type='application/json', dumps=None, **kwargs)

Bases: HTTPResponse

Convenience class for JSON responses

HTTP response to be sent back to the client, when the response is of json type. Offers several utilities to manipulate common json data types.

Args:

body (Optional[Any], optional): The body content to be returned. Defaults to None. status (int, optional): HTTP response number. Defaults to 200. headers (Optional[Union[Header, Dict[str, str]]], optional): Headers to be returned. Defaults to None. content_type (str, optional): Content type to be returned (as a header). Defaults to β€œapplication/json”. dumps (Optional[Callable[…, str]], optional): The function to use for json encoding. Defaults to None. **kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to {}.

Parameters:
  • body (Optional[Any]) –

  • status (int) –

  • headers (Optional[Union[Header, Dict[str, str]]]) –

  • content_type (str) –

  • dumps (Optional[Callable[..., str]]) –

  • kwargs (Any) –

append(value)

Appends a value to the response raw_body, ensuring that body is kept up to date.

This can only be used if raw_body is a list.

Args:

value (Any): The value to append

Raises:

SanicException: If the body is not a list

Parameters:

value (Any) –

Return type:

None

extend(value)

Extends the response’s raw_body with the given values, ensuring that body is kept up to date.

This can only be used if raw_body is a list.

Args:

value (Any): The values to extend with

Raises:

SanicException: If the body is not a list

Parameters:

value (Any) –

Return type:

None

pop(key, default=<Default>)

Pops a key from the response’s raw_body, ensuring that body is kept up to date.

This can only be used if raw_body is a dict or a list.

Args:

key (Any): The key to pop default (Any, optional): The default value to return if the key is not found. Defaults to _default.

Raises:

SanicException: If the body is not a dict or a list TypeError: If the body is a list and a default value is provided

Returns:

Any: The value that was popped

Parameters:
  • key (Any) –

  • default (Any) –

Return type:

Any

set_body(body, dumps=None, **dumps_kwargs)

Set the response body to the given value, using the given dumps function

Sets a new response body using the given dumps function and kwargs, or falling back to the defaults given when creating the object if none are specified.

Args:

body (Any): The body to set dumps (Optional[Callable[…, str]], optional): The function to use for json encoding. Defaults to None. **dumps_kwargs (Any, optional): The kwargs to pass to the json encoding function. Defaults to {}.

Examples:

`python response = JSONResponse({"foo": "bar"}) response.set_body({"bar": "baz"}) assert response.body == b'{"bar": "baz"}' `

Parameters:
  • body (Any) –

  • dumps (Callable[[...], str] | None) –

  • dumps_kwargs (Any) –

Return type:

None

update(*args, **kwargs)

Updates the response’s raw_body with the given values, ensuring that body is kept up to date.

This can only be used if raw_body is a dict.

Args:

*args: The args to update with **kwargs: The kwargs to update with

Raises:

SanicException: If the body is not a dict

Return type:

None

property body: bytes | None

Returns the response body.

Returns:

Optional[bytes]: The response body

property raw_body: Any | None

Returns the raw body, as long as body has not been manually set previously.

NOTE: This object should not be mutated, as it will not be reflected in the response body. If you need to mutate the response body, consider using one of the provided methods in this class or alternatively call set_body() with the mutated object afterwards or set the raw_body property to it.

Returns:

Optional[Any]: The raw body

class sanic.response.ResponseStream(streaming_fn, status=200, headers=None, content_type=None)

Bases: object

A compat layer to bridge the gap after the deprecation of StreamingHTTPResponse.

It will be removed when: - file_stream is moved to new style streaming - file and file_stream are combined into a single API

Parameters:
  • streaming_fn (Callable[[Union[BaseHTTPResponse, ResponseStream]], Coroutine[Any, Any, None]]) –

  • status (int) –

  • headers (Optional[Union[Header, Dict[str, str]]]) –

  • content_type (Optional[str]) –

sanic.response.empty(status=204, headers=None)

Returns an empty response to the client.

Args:

status (int, optional): HTTP response code. Defaults to 204. headers ([type], optional): Custom HTTP headers. Defaults to None.

Returns:

HTTPResponse: An empty response to the client.

Parameters:
  • status (int) –

  • headers (Dict[str, str] | None) –

Return type:

HTTPResponse

async sanic.response.file(location, status=200, request_headers=None, validate_when_requested=True, mime_type=None, headers=None, filename=None, last_modified=<Default>, max_age=None, no_store=None, _range=None)

Return a response object with file data.

Args:

location (Union[str, PurePath]): Location of file on system. status (int, optional): HTTP response code. Won’t enforce the passed in status if only a part of the content will be sent (206) or file is being validated (304). Defaults to 200. request_headers (Optional[Header], optional): The request headers. validate_when_requested (bool, optional): If True, will validate the file when requested. Defaults to True. mime_type (Optional[str], optional): Specific mime_type. headers (Optional[Dict[str, str]], optional): Custom Headers. filename (Optional[str], optional): Override filename. last_modified (Optional[Union[datetime, float, int, Default]], optional): The last modified date and time of the file. max_age (Optional[Union[float, int]], optional): Max age for cache control. no_store (Optional[bool], optional): Any cache should not store this response. Defaults to None. _range (Optional[Range], optional):

Returns:

HTTPResponse: The response object with the file data.

Parameters:
  • location (str | PurePath) –

  • status (int) –

  • request_headers (Header | None) –

  • validate_when_requested (bool) –

  • mime_type (str | None) –

  • headers (Dict[str, str] | None) –

  • filename (str | None) –

  • last_modified (datetime | float | int | Default | None) –

  • max_age (int | float | None) –

  • no_store (bool | None) –

  • _range (Range | None) –

Return type:

HTTPResponse

async sanic.response.file_stream(location, status=200, chunk_size=4096, mime_type=None, headers=None, filename=None, _range=None)

Return a streaming response object with file data.

Parameters:
  • location (str | PurePath) – Location of file on system.

  • chunk_size (int) – The size of each chunk in the stream (in bytes)

  • mime_type (str | None) – Specific mime_type.

  • headers (Dict[str, str] | None) – Custom Headers.

  • filename (str | None) – Override filename.

  • _range (Range | None) –

  • status (int) –

Return type:

ResponseStream

Args:

location (Union[str, PurePath]): Location of file on system. status (int, optional): HTTP response code. Won’t enforce the passed in status if only a part of the content will be sent (206) or file is being validated (304). Defaults to 200. chunk_size (int, optional): The size of each chunk in the stream (in bytes). Defaults to 4096. mime_type (Optional[str], optional): Specific mime_type. headers (Optional[Dict[str, str]], optional): Custom HTTP headers. filename (Optional[str], optional): Override filename. _range (Optional[Range], optional): The range of bytes to send.

sanic.response.html(body, status=200, headers=None)

Returns response object with body in html format.

Body should be a str or bytes like object, or an object with __html__ or _repr_html_.

Args:

body (Union[str, bytes, HTMLProtocol]): Response data. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None.

Returns:

HTTPResponse: A response object with body in html format.

Parameters:
  • body (str | bytes | HTMLProtocol) –

  • status (int) –

  • headers (Dict[str, str] | None) –

Return type:

HTTPResponse

sanic.response.json(body, status=200, headers=None, content_type='application/json', dumps=None, **kwargs)

Returns response object with body in json format.

Args:

body (Any): Response data to be serialized. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None. content_type (str, optional): The content type (string) of the response. Defaults to β€œapplication/json”. dumps (Callable[…, str], optional): A custom json dumps function. Defaults to None. **kwargs (Any): Remaining arguments that are passed to the json encoder.

Returns:

JSONResponse: A response object with body in json format.

Parameters:
  • body (Any) –

  • status (int) –

  • headers (Dict[str, str] | None) –

  • content_type (str) –

  • dumps (Callable[[...], str] | None) –

  • kwargs (Any) –

Return type:

JSONResponse

sanic.response.json_dumps()

Converts arbitrary object recursively into JSON. Use ensure_ascii=false to output UTF-8. Set encode_html_chars=True to encode < > & as unicode escape sequences. Set escape_forward_slashes=False to prevent escaping / characters.Set allow_nan=False to raise an exception when NaN or Infinity would be serialized.Set reject_bytes=True to raise TypeError on bytes.

sanic.response.raw(body, status=200, headers=None, content_type='application/octet-stream')

Returns response object without encoding the body.

Args:

body (Optional[AnyStr]): Response data. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None. content_type (str, optional): The content type (string) of the response. Defaults to β€œapplication/octet-stream”.

Returns:

HTTPResponse: A response object without encoding the body.

Parameters:
  • body (AnyStr | None) –

  • status (int) –

  • headers (Dict[str, str] | None) –

  • content_type (str) –

Return type:

HTTPResponse

sanic.response.redirect(to, headers=None, status=302, content_type='text/html; charset=utf-8')

Cause a HTTP redirect (302 by default) by setting a Location header.

Args:

to (str): path or fully qualified URL to redirect to headers (Optional[Dict[str, str]], optional): optional dict of headers to include in the new request. Defaults to None. status (int, optional): status code (int) of the new request, defaults to 302. Defaults to 302. content_type (str, optional): the content type (string) of the response. Defaults to β€œtext/html; charset=utf-8”.

Returns:

HTTPResponse: A response object with the redirect.

Parameters:
  • to (str) –

  • headers (Dict[str, str] | None) –

  • status (int) –

  • content_type (str) –

Return type:

HTTPResponse

sanic.response.text(body, status=200, headers=None, content_type='text/plain; charset=utf-8')

Returns response object with body in text format.

Args:

body (str): Response data. status (int, optional): HTTP response code. Defaults to 200. headers (Dict[str, str], optional): Custom HTTP headers. Defaults to None. content_type (str, optional): The content type (string) of the response. Defaults to β€œtext/plain; charset=utf-8”.

Returns:

HTTPResponse: A response object with body in text format.

Raises:

TypeError: If the body is not a string.

Parameters:
  • body (str) –

  • status (int) –

  • headers (Dict[str, str] | None) –

  • content_type (str) –

Return type:

HTTPResponse

async sanic.response.validate_file(request_headers, last_modified)

Validate file based on request headers.

Args:

request_headers (Header): The request headers. last_modified (Union[datetime, float, int]): The last modified date and time of the file.

Returns:

Optional[HTTPResponse]: A response object with status 304 if the file is not modified.

Parameters:
  • request_headers (Header) –

  • last_modified (datetime | float | int) –

Return type:

HTTPResponse | None

sanic.views

class sanic.views.HTTPMethodView

Bases: object

Class based implementation for creating and grouping handlers

Class-based views (CBVs) are an alternative to function-based views. They allow you to reuse common logic, and group related views, while keeping the flexibility of function-based views.

To use a class-based view, subclass the method handler, and implement methods (get, post, put, patch, delete) for the class to correspond to each HTTP method you want to support.

For example:

```python class DummyView(HTTPMethodView):

def get(self, request: Request):

return text(β€˜I am get method’)

def put(self, request: Request):

return text(β€˜I am put method’)

```

If someone tries to use a non-implemented method, they will reveive a 405 response.

If you need any url params just include them in method signature, like you would for function-based views.

```python class DummyView(HTTPMethodView):

def get(self, request: Request, my_param_here: str):

return text(f”I am get method with {my_param_here}”)

```

Next, you need to attach the view to the app or blueprint. You can do this in the exact same way as you would for a function-based view, except you should you use MyView.as_view() instead of my_view_handler.

`python app.add_route(DummyView.as_view(), "/<my_param_here>") `

Alternatively, you can use the attach method:

`python DummyView.attach(app, "/<my_param_here>") `

Or, at the time of subclassing:

```python class DummyView(HTTPMethodView, attach=app, uri=”/<my_param_here>”):

…

```

To add a decorator, you can either:

  1. Add it to the decorators list on the class, which will apply it to

    all methods on the class; or

  2. Add it to the method directly, which will only apply it to that method.

```python class DummyView(HTTPMethodView):

decorators = [my_decorator] …

# or

class DummyView(HTTPMethodView):

@my_decorator def get(self, request: Request):

…

```

One catch is that you need to be mindful that the call inside the decorator may need to account for the self argument, which is passed to the method as the first argument. Alternatively, you may want to also mark your method as staticmethod to avoid this.

Available attributes at the time of subclassing: - attach (Optional[Union[Sanic, Blueprint]]): The app or blueprint to

attach the view to.

  • uri (str): The uri to attach the view to.

  • methods (Iterable[str]): The HTTP methods to attach the view to.

    Defaults to {β€œGET”}.

  • host (Optional[str]): The host to attach the view to.

  • strict_slashes (Optional[bool]): Whether to add a redirect rule for

    the uri with a trailing slash.

  • version (Optional[int]): The version to attach the view to.

  • name (Optional[str]): The name to attach the view to.

  • stream (bool): Whether the view is a stream handler.

  • version_prefix (str): The prefix to use for the version. Defaults

    to β€œ/v”.

classmethod as_view(*class_args, **class_kwargs)

Return view function for use with the routing system, that dispatches request to appropriate handler method.

If you need to pass arguments to the class’s constructor, you can pass the arguments to as_view and they will be passed to the class __init__ method.

Args:

*class_args: Variable length argument list for the class instantiation. **class_kwargs: Arbitrary keyword arguments for the class instantiation.

Returns:

RouteHandler: The view function.

Examples:

```python class DummyView(HTTPMethodView):

def __init__(self, foo: MyFoo):

self.foo = foo

async def get(self, request: Request):

return text(self.foo.bar)

app.add_route(DummyView.as_view(foo=MyFoo()), β€œ/”) ```

Parameters:
  • class_args (Any) –

  • class_kwargs (Any) –

Return type:

Callable[[…], Coroutine[Any, Any, HTTPResponse | None]]

classmethod attach(to, uri, methods=frozenset({'GET'}), host=None, strict_slashes=None, version=None, name=None, stream=False, version_prefix='/v')

Attaches the view to a Sanic app or Blueprint at the specified URI.

Args:

cls: The class that this method is part of. to (Union[Sanic, Blueprint]): The Sanic application or Blueprint to attach to. uri (str): The URI to bind the view to. methods (Iterable[str], optional): A collection of HTTP methods that the view should respond to. Defaults to frozenset({β€œGET”}). host (Optional[str], optional): A specific host or hosts to bind the view to. Defaults to None. strict_slashes (Optional[bool], optional): Enforce or not the trailing slash. Defaults to None. version (Optional[int], optional): Version of the API if versioning is used. Defaults to None. name (Optional[str], optional): Unique name for the route. Defaults to None. stream (bool, optional): Enable or disable streaming for the view. Defaults to False. version_prefix (str, optional): The prefix for the version, if versioning is used. Defaults to β€œ/v”.

Parameters:
  • to (Union[Sanic, Blueprint]) –

  • uri (str) –

  • methods (Iterable[str]) –

  • host (Optional[str]) –

  • strict_slashes (Optional[bool]) –

  • version (Optional[int]) –

  • name (Optional[str]) –

  • stream (bool) –

  • version_prefix (str) –

Return type:

None

dispatch_request(request, *args, **kwargs)

Dispatch request to appropriate handler method.

Parameters:

request (Request) –

sanic.views.stream(func)

Decorator to mark a function as a stream handler.