Table of Contents
Filesanic.request.formparse_multipart_formsanic.request.formRequestParameterssanic.request.parametersRequestsanic.request.typessanic.request.form.File#
Model for defining a file.
class File(type: ForwardRef('str'), body: ForwardRef('bytes'), name: ForwardRef('str'))
It is a namedtuple
, therefore you can iterate over the object, or
access the parameters by name.
Parameters
- type
str The mimetype, defaults to "text/plain".
- body
bytes Bytes of the file.
- name
str The filename.
sanic.request.form.parse_multipart_form#
Parse a request body and returns fields and files
def parse_multipart_form(body, boundary)
Parameters
- body
bytes Bytes request body.
- boundary
bytes Bytes multipart boundary.
Return
- Tuple[RequestParameters, RequestParameters]
A tuple containing fields and files as
RequestParameters
.
sanic.request.parameters.RequestParameters#
Hosts a dict with lists as values where get returns the first value of the list and getlist returns the whole shebang
class RequestParameters(self)
get#
Return the first value, either the default or actual
def get(self, name: str, default: Optional[Any] = None): -> Optional[Any]
Parameters
- name
str The name of the parameter
- default
Optional[Any] The default value. Defaults to None.
Return
- Optional[Any]
The first value of the list
getlist#
Return the entire list
def getlist(self, name: str, default: Optional[Any] = None): -> Optional[Any]
Parameters
- name
str The name of the parameter
- default
Optional[Any] The default value. Defaults to None.
Return
- Optional[Any]
The entire list
sanic.request.types.Request#
State of HTTP request.
class Request(url_bytes: bytes, headers: Header, version: str, method: str, transport: TransportProtocol, app: sanic_type, head: bytes = b'', stream_id: int = 0)
Parameters
- 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 Request head. Defaults to
b""
.
- stream_id
int HTTP/3 stream ID. Defaults to
0
.
accept#
Accepted response content types.
@property
def accept(self): -> AcceptList
A convenience handler for easier RFC-compliant matching of MIME types, parsed as a list that can match wildcards and includes / by default.
Return
- AcceptList
Accepted response content types
args#
Parse query_string
using urllib.parse.parse_qs
.
@property
def args(self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace"): -> RequestParameters
This methods is used by the args
property, but it also
can be used directly if you need to change default parameters.
Parameters
- 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 defaultFalse
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. IfTrue
, errors raise aValueError
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.
Return
- RequestParameters
A dictionary containing the parsed arguments.
client_ip#
Client IP address.
@property
def client_ip(self): -> str
- proxied remote address
self.forwarded['for']
- 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).
Return
- str
IPv4, bracketed IPv6, UNIX socket name or arbitrary string
content_type#
Content-Type header form the request
@property
def content_type(self): -> str
Return
- str
Content-Type header form the request
cookies#
Incoming cookies on the request
@property
def cookies(self): -> RequestParameters
Return
- RequestParameters
Incoming cookies on the request
credentials#
Attempt to return the auth header value.
@property
def credentials(self): -> Optional[Credentials]
Covers NoAuth, Basic Auth, Bearer Token, Api Token authentication schemas.
Return
- Optional[Credentials]
A Credentials object with token, or username and password related to the request
ctx#
The current request context.
@property
def ctx(self): -> ctx_type
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.
Return
- ctx_type
The current request context.
endpoint#
Alias of sanic.request.Request.name
@property
def endpoint(self): -> Optional[str]
Return
- Optional[str]
The route name
files#
The request body parsed as uploaded files
@property
def files(self): -> Optional[RequestParameters]
Return
- Optional[RequestParameters]
The request body parsed as uploaded files
form#
The request body parsed as form data
@property
def form(self): -> Optional[RequestParameters]
Return
- Optional[RequestParameters]
The request body parsed as form data
forwarded#
Active proxy information obtained from request headers, as specified in Sanic configuration.
@property
def forwarded(self): -> Options
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.
Return
- Options
proxy information from request headers
generate_id#
Generate a unique ID for the request.
@classmethod
def generate_id(_): -> Union[uuid.UUID, str, int]
This method is called to generate a unique ID for each request.
By default, it returns a uuid.UUID
instance.
Return
- Union[uuid.UUID, str, int]
A unique ID for the request.
get_args#
Parse query_string
using urllib.parse.parse_qs
.
def get_args(self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace"): -> RequestParameters
This methods is used by the args
property, but it also
can be used directly if you need to change default parameters.
Parameters
- 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 defaultFalse
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. IfTrue
, errors raise aValueError
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.
Return
- RequestParameters
A dictionary containing the parsed arguments.
get_cookies#
def get_cookies(self): -> RequestParameters
get_current#
Retrieve the current request object
@classmethod
def get_current(): -> Request
This implements Context Variables 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:
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)
Return
- Request
The current request object
Raises
- sanic.exceptions.ServerError
If it is outside of a request lifecycle.
get_form#
Method to extract and parse the form data from a request.
def get_form(self, keep_blank_values: bool = False): -> Optional[RequestParameters]
Parameters
- keep_blank_values
bool Whether to discard blank values from the form data.
Return
- Optional[RequestParameters]
The parsed form data.
get_query_args#
Parse query_string
using urllib.parse.parse_qsl
.
def get_query_args(self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace"): -> list
This methods is used by query_args
propertyn but can be used
directly if you need to change default parameters.
Parameters
- 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 defaultFalse
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. IfTrue
, errors raise aValueError
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.
Return
- list
A list of tuples containing the parsed arguments.
host#
The currently effective server 'host' (hostname or hostname:port).
@property
def host(self): -> str
config.SERVER_NAME
overrides any client headers- proxied host of original request
- request host header
hostname and port may be separated by
sanic.headers.parse_host(request.host)
.
Return
- str
the first matching host found, or empty string
id#
A request ID passed from the client, or generated from the backend.
@property
def id(self): -> Optional[Union[uuid.UUID, str, int]]
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.
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)
Return
- Optional[Union[uuid.UUID, str, int]]
A request ID passed from the client, or generated from the backend.
is_cacheable#
Whether the HTTP method is cacheable.
@property
def is_cacheable(self): -> bool
See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.3
Return
- bool
Whether the HTTP method is cacheable.
is_idempotent#
Whether the HTTP method is iempotent.
@property
def is_idempotent(self): -> bool
See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.2
Return
- bool
Whether the HTTP method is iempotent.
is_safe#
Whether the HTTP method is safe.
@property
def is_safe(self): -> bool
See https://datatracker.ietf.org/doc/html/rfc7231#section-4.2.1
Return
- bool
Whether the HTTP method is safe.
json#
The request body parsed as JSON
@property
def json(self): -> Any
Return
- Any
The request body parsed as JSON
load_json#
Load the request body as JSON
def load_json(self, loads = None): -> Any
Parameters
- loads
Callable A custom JSON loader. Defaults to None.
Return
- Any
The request body parsed as JSON
Raises
- BadRequest
If the request body cannot be parsed as JSON
make_context#
Create a new context object.
@staticmethod
def make_context(): -> ctx_type
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.
Return
- ctx_type
A new context object.
match_info#
Matched path parameters after resolving route
@property
def match_info(self): -> Dict[str, Any]
Return
- Dict[str, Any]
Matched path parameters after resolving route
name#
The route name
@property
def name(self): -> Optional[str]
In the following pattern:
<AppName>.[<BlueprintName>.]<HandlerName>
Return
- Optional[str]
The route name
network_paths#
Access the network paths if available
@property
def network_paths(self): -> Optional[List[Any]]
Return
- Optional[List[Any]]
Access the network paths if available
path#
Path of the local HTTP request
@property
def path(self): -> str
Return
- str
Path of the local HTTP request
protocol#
The HTTP protocol instance
@property
def protocol(self): -> TransportProtocol
Return
- Protocol
The HTTP protocol instance
query_args#
Parse query_string
using urllib.parse.parse_qsl
.
@property
def query_args(self, keep_blank_values: bool = False, strict_parsing: bool = False, encoding: str = "utf-8", errors: str = "replace"): -> list
This methods is used by query_args
propertyn but can be used
directly if you need to change default parameters.
Parameters
- 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 defaultFalse
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. IfTrue
, errors raise aValueError
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.
Return
- list
A list of tuples containing the parsed arguments.
query_string#
Representation of the requested query
@property
def query_string(self): -> str
Return
- str
Representation of the requested query
raw_headers#
The unparsed HTTP headers
@property
def raw_headers(self): -> bytes
Return
- bytes
The unparsed HTTP headers
receive_body#
Receive request.body, if not already received.
async def receive_body(self)
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.
remote_addr#
Client IP address, if available from proxy.
@property
def remote_addr(self): -> str
Return
- str
IPv4, bracketed IPv6, UNIX socket name or arbitrary string
request_line#
The first line of a HTTP request
@property
def request_line(self): -> bytes
Return
- bytes
The first line of a HTTP request
reset_response#
Reset the response object.
def reset_response(self): -> None
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.
respond#
Respond to the request without returning.
async def respond(self, response: Optional[BaseHTTPResponse] = None, status: int = 200, headers: Optional[Union[Header, Dict[str, str]]] = None, content_type: Optional[str] = None)
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:
@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:
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()
Parameters
- 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.
Return
- FinalResponseType
Final response being sent (may be different from the "response" parameter because of middlewares), which can be used to manually send data.
scheme#
Determine request scheme.
@property
def scheme(self): -> str
config.SERVER_NAME
if in full URL format- proxied proto/scheme
- local connection protocol
Return
- str
http|https|ws|wss or arbitrary value given by the headers.
scope#
The ASGI scope of the request.
@property
def scope(self): -> ASGIScope
Return
- ASGIScope
The ASGI scope of the request.
Raises
- NotImplementedError
If the app isn't an ASGI app.
server_name#
hostname the client connected to, by request.host
@property
def server_name(self): -> str
Return
- str
hostname the client connected to, by
request.host
server_path#
Full path of current URL; uses proxied or local path
@property
def server_path(self): -> str
Return
- str
Full path of current URL; uses proxied or local path
server_port#
The port the client connected to, by forwarded port
or request.host
.
@property
def server_port(self): -> int
Default port is returned as 80 and 443 based on request.scheme
.
Return
- int
The port the client connected to, by forwarded
port
orrequest.host
.
socket#
Information about the connected socket if available
@property
def socket(self): -> Union[Tuple[str, int], Tuple[None, None]]
Return
- Tuple[Optional[str], Optional[int]]
Information about the connected socket if available, in the form of a tuple of (ip, port)
stream_id#
Access the HTTP/3 stream ID.
@property
def stream_id(self): -> int
Return
- int
The HTTP/3 stream ID.
Raises
- sanic.exceptions.ServerError
If the request is not HTTP/3.
token#
Attempt to return the auth header token.
@property
def token(self): -> Optional[str]
Return
- Optional[str]
The auth header token
uri_template#
The defined URI template
@property
def uri_template(self): -> Optional[str]
Return
- Optional[str]
The defined URI template
url_for#
Retrieve a URL for a given view name.
def url_for(self, view_name: str, kwargs): -> str
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.
Parameters
- view_name
str The view name to generate URL for.
- **kwargs
Arbitrary keyword arguments to build URL query string.
Return
- str
The generated URL.