ASGI Request & Response¶
Instances of the falcon.asgi.Request
and
falcon.asgi.Response
classes are passed into responders as
the second and third arguments, respectively:
import falcon.asgi
class Resource:
async def on_get(self, req, resp):
resp.media = {'message': 'Hello world!'}
resp.status = 200
# -- snip --
app = falcon.asgi.App()
app.add_route('/', Resource())
Request¶
- class falcon.asgi.Request(scope, receive, first_event=None, options=None)[source]¶
Represents a client’s HTTP request.
Note
Request is not meant to be instantiated directly by responders.
- Parameters
scope (dict) – ASGI HTTP connection scope passed in from the server (see also: Connection Scope).
receive (awaitable) – ASGI awaitable callable that will yield a new event dictionary when one is available.
- Keyword Arguments
first_event (dict) – First ASGI event received from the client, if one was preloaded (default
None
).options (falcon.request.RequestOptions) – Set of global request options passed from the App handler.
- scope¶
Reference to the ASGI HTTP connection scope passed in from the server (see also: Connection Scope).
- Type
- context¶
Empty object to hold any data (in its attributes) about the request which is specific to your app (e.g. session object). Falcon itself will not interact with this attribute after it has been initialized.
Note
The preferred way to pass request-specific data, when using the default context type, is to set attributes directly on the context object. For example:
req.context.role = 'trial' req.context.user = 'guest'
- Type
- context_type¶
Class variable that determines the factory or type to use for initializing the context attribute. By default, the framework will instantiate bare objects (instances of the bare
falcon.Context
class). However, you may override this behavior by creating a custom child class offalcon.asgi.Request
, and then passing that new class to falcon.asgi.App() by way of the latter’s request_type parameter.Note
When overriding context_type with a factory function (as opposed to a class), the function is called like a method of the current
Request
instance. Therefore the first argument is the Request instance itself (i.e., self).- Type
class
- scheme¶
URL scheme used for the request. One of
'http'
,'https'
,'ws'
, or'wss'
. Defaults to'http'
for thehttp
scope, or'ws'
for thewebsocket
scope, when the ASGI server does not include the scheme in the connection scope.Note
If the request was proxied, the scheme may not match what was originally requested by the client.
forwarded_scheme
can be used, instead, to handle such cases.- Type
- forwarded_scheme¶
Original URL scheme requested by the user agent, if the request was proxied. Typical values are
'http'
or'https'
.The following request headers are checked, in order of preference, to determine the forwarded scheme:
Forwarded
X-Forwarded-For
If none of these headers are available, or if the Forwarded header is available but does not contain a “proto” parameter in the first hop, the value of
scheme
is returned instead.(See also: RFC 7239, Section 1)
- Type
- host¶
Host request header field, if present. If the Host header is missing, this attribute resolves to the ASGI server’s listening host name or IP address.
- Type
- forwarded_host¶
Original host request header as received by the first proxy in front of the application server.
The following request headers are checked, in order of preference, to determine the forwarded scheme:
Forwarded
X-Forwarded-Host
If none of the above headers are available, or if the Forwarded header is available but the “host” parameter is not included in the first hop, the value of
host
is returned instead.Note
Reverse proxies are often configured to set the Host header directly to the one that was originally requested by the user agent; in that case, using
host
is sufficient.(See also: RFC 7239, Section 4)
- Type
- port¶
Port used for the request. If the Host header is present in the request, but does not specify a port, the default one for the given schema is returned (80 for HTTP and 443 for HTTPS). If the request does not include a Host header, the listening port for the ASGI server is returned instead.
- Type
- netloc¶
Returns the “host:port” portion of the request URL. The port may be omitted if it is the default one for the URL’s schema (80 for HTTP and 443 for HTTPS).
- Type
- subdomain¶
Leftmost (i.e., most specific) subdomain from the hostname. If only a single domain name is given, subdomain will be
None
.Note
If the hostname in the request is an IP address, the value for subdomain is undefined.
- Type
- root_path¶
The initial portion of the request URI’s path that corresponds to the application object, so that the application knows its virtual “location”. This may be an empty string, if the application corresponds to the “root” of the server.
(Corresponds to the “root_path” ASGI HTTP scope field.)
- Type
- forwarded_uri¶
Original URI for proxied requests. Uses
forwarded_scheme
andforwarded_host
in order to reconstruct the original URI requested by the user agent.- Type
- relative_uri¶
The path and query string portion of the request URI, omitting the scheme and host.
- Type
- forwarded_prefix¶
The prefix of the original URI for proxied requests. Uses
forwarded_scheme
andforwarded_host
in order to reconstruct the original URI.- Type
- path¶
Path portion of the request URI (not including query string).
Warning
If this attribute is to be used by the app for any upstream requests, any non URL-safe characters in the path must be URL encoded back before making the request.
Note
req.path
may be set to a new value by aprocess_request()
middleware method in order to influence routing. If the original request path was URL encoded, it will be decoded before being returned by this attribute.- Type
- query_string¶
Query string portion of the request URI, without the preceding ‘?’ character.
- Type
- uri_template¶
The template for the route that was matched for this request. May be
None
if the request has not yet been routed, as would be the case forprocess_request()
middleware methods. May also beNone
if your app uses a custom routing engine and the engine does not provide the URI template when resolving a route.- Type
- remote_addr¶
IP address of the closest known client or proxy to the ASGI server, or
'127.0.0.1'
if unknown.This property’s value is equivalent to the last element of the
access_route
property.- Type
- access_route¶
IP address of the original client (if known), as well as any known addresses of proxies fronting the ASGI server.
The following request headers are checked, in order of preference, to determine the addresses:
Forwarded
X-Forwarded-For
X-Real-IP
In addition, the value of the “client” field from the ASGI connection scope will be appended to the end of the list if not already included in one of the above headers. If the “client” field is not available, it will default to
'127.0.0.1'
.Note
Per RFC 7239, the access route may contain “unknown” and obfuscated identifiers, in addition to IPv4 and IPv6 addresses
Warning
Headers can be forged by any client or proxy. Use this property with caution and validate all values before using them. Do not rely on the access route to authorize requests!
- Type
- forwarded¶
Value of the Forwarded header, as a parsed list of
falcon.Forwarded
objects, orNone
if the header is missing. If the header value is malformed, Falcon will make a best effort to parse what it can.(See also: RFC 7239, Section 4)
- Type
- date¶
Value of the Date header, converted to a
datetime
instance. The header value is assumed to conform to RFC 1123.- Type
datetime
- client_accepts_json¶
True
if the Accept header indicates that the client is willing to receive JSON, otherwiseFalse
.- Type
- client_accepts_msgpack¶
True
if the Accept header indicates that the client is willing to receive MessagePack, otherwiseFalse
.- Type
- client_accepts_xml¶
True
if the Accept header indicates that the client is willing to receive XML, otherwiseFalse
.- Type
- cookies¶
A dict of name/value cookie pairs. The returned object should be treated as read-only to avoid unintended side-effects. If a cookie appears more than once in the request, only the first value encountered will be made available here.
See also:
get_cookie_values()
- Type
- content_length¶
Value of the Content-Length header converted to an
int
, orNone
if the header is missing.- Type
- stream¶
File-like input object for reading the body of the request, if any.
See also:
falcon.asgi.BoundedStream
- media¶
An awaitable property that acts as an alias for
get_media()
. This can be used to ease the porting of a WSGI app to ASGI, although theawait
keyword must still be added when referencing the property:deserialized_media = await req.media
- Type
- range¶
A 2-member
tuple
parsed from the value of the Range header.The two members correspond to the first and last byte positions of the requested resource, inclusive. Negative indices indicate offset from the end of the resource, where -1 is the last byte, -2 is the second-to-last byte, and so forth.
Only continuous ranges are supported (e.g., “bytes=0-0,-1” would result in an HTTPBadRequest exception when the attribute is accessed.)
- Type
tuple of int
- range_unit¶
Unit of the range parsed from the value of the Range header, or
None
if the header is missing- Type
- if_match¶
Value of the If-Match header, as a parsed list of
falcon.ETag
objects orNone
if the header is missing or its value is blank.This property provides a list of all
entity-tags
in the header, both strong and weak, in the same order as listed in the header.(See also: RFC 7232, Section 3.1)
- Type
- if_none_match¶
Value of the If-None-Match header, as a parsed list of
falcon.ETag
objects orNone
if the header is missing or its value is blank.This property provides a list of all
entity-tags
in the header, both strong and weak, in the same order as listed in the header.(See also: RFC 7232, Section 3.2)
- Type
- if_modified_since¶
Value of the If-Modified-Since header, or
None
if the header is missing.- Type
datetime
- if_unmodified_since¶
Value of the If-Unmodified-Since header, or
None
if the header is missing.- Type
datetime
- headers¶
Raw HTTP headers from the request with canonical dash-separated names. Parsing all the headers to create this dict is done the first time this attribute is accessed, and the returned object should be treated as read-only. Note that this parsing can be costly, so unless you need all the headers in this format, you should instead use the
get_header()
method or one of the convenience attributes to get a value for a specific header.- Type
- params¶
The mapping of request query parameter names to their values. Where the parameter appears multiple times in the query string, the value mapped to that parameter key will be a list of all the values in the order seen.
- Type
- options¶
Set of global options passed in from the App handler.
- client_prefers(media_types)[source]¶
Return the client’s preferred media type, given several choices.
- Parameters
media_types (iterable of str) – One or more Internet media types from which to choose the client’s preferred type. This value must be an iterable collection of strings.
- Returns
The client’s preferred media type, based on the Accept header. Returns
None
if the client does not accept any of the given types.- Return type
- get_cookie_values(name)[source]¶
Return all values provided in the Cookie header for the named cookie.
(See also: Getting Cookies)
- Parameters
name (str) – Cookie name, case-sensitive.
- Returns
Ordered list of all values specified in the Cookie header for the named cookie, or
None
if the cookie was not included in the request. If the cookie is specified more than once in the header, the returned list of values will preserve the ordering of the individualcookie-pair
’s in the header.- Return type
- get_header(name, required=False, default=None)[source]¶
Retrieve the raw string value for the given header.
- Parameters
name (str) – Header name, case-insensitive (e.g., ‘Content-Type’)
- Keyword Arguments
- Returns
The value of the specified header if it exists, or the default value if the header is not found and is not required.
- Return type
- Raises
HTTPBadRequest – The header was not found in the request, but it was required.
- get_header_as_datetime(header, required=False, obs_date=False)[source]¶
Return an HTTP header with HTTP-Date values as a datetime.
- Parameters
name (str) – Header name, case-insensitive (e.g., ‘Date’)
- Keyword Arguments
- Returns
The value of the specified header if it exists, or
None
if the header is not found and is not required.- Return type
datetime
- Raises
HTTPBadRequest – The header was not found in the request, but it was required.
HttpInvalidHeader – The header contained a malformed/invalid value.
- async get_media(default_when_empty=<object object>)[source]¶
Return a deserialized form of the request stream.
The first time this method is called, the request stream will be deserialized using the Content-Type header as well as the media-type handlers configured via
falcon.RequestOptions
. The result will be cached and returned in subsequent calls:deserialized_media = await req.get_media()
If the matched media handler raises an error while attempting to deserialize the request body, the exception will propagate up to the caller.
See also Media for more information regarding media handling.
Note
When
get_media
is called on a request with an empty body, Falcon will let the media handler try to deserialize the body and will return the value returned by the handler or propagate the exception raised by it. To instead return a different value in case of an exception by the handler, specify the argumentdefault_when_empty
.Warning
This operation will consume the request stream the first time it’s called and cache the results. Follow-up calls will just retrieve a cached version of the object.
- Parameters
default_when_empty – Fallback value to return when there is no body in the request and the media handler raises an error (like in the case of the default JSON media handler). By default, Falcon uses the value returned by the media handler or propagates the raised exception, if any. This value is not cached, and will be used only for the current call.
- Returns
The deserialized media representation.
- Return type
media (object)
- get_param(name, required=False, store=None, default=None)[source]¶
Return the raw value of a query string parameter as a string.
Note
If an HTML form is POSTed to the API using the application/x-www-form-urlencoded media type, Falcon can automatically parse the parameters from the request body via
get_media()
.See also: How can I access POSTed form params?
Note
Similar to the way multiple keys in form data are handled, if a query parameter is included in the query string multiple times, only one of those values will be returned, and it is undefined which one. This caveat also applies when
auto_parse_qs_csv
is enabled and the given parameter is assigned to a comma-separated list of values (e.g.,foo=a,b,c
).When multiple values are expected for a parameter,
get_param_as_list()
can be used to retrieve all of them at once.- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘sort’).
- Keyword Arguments
required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is present.default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param as a string, or
None
if param is not found and is not required.- Return type
- Raises
HTTPBadRequest – A required param is missing from the request.
- get_param_as_bool(name, required=False, store=None, blank_as_true=True, default=None)[source]¶
Return the value of a query string parameter as a boolean.
This method treats valueless parameters as flags. By default, if no value is provided for the parameter in the query string,
True
is assumed and returned. If the parameter is missing altogether,None
is returned as with otherget_param_*()
methods, which can be easily treated as falsy by the caller as needed.The following boolean strings are supported:
TRUE_STRINGS = ('true', 'True', 't', 'yes', 'y', '1', 'on') FALSE_STRINGS = ('false', 'False', 'f', 'no', 'n', '0', 'off')
- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘detailed’).
- Keyword Arguments
required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found or is not a recognized boolean string (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).blank_as_true (bool) – Valueless query string parameters are treated as flags, resulting in
True
being returned when such a parameter is present, andFalse
otherwise. To require the client to explicitly opt-in to a truthy value, passblank_as_true=False
to returnFalse
when a value is not specified in the query string.default (any) – If the param is not found, return this value instead of
None
.
- Returns
The value of the param if it is found and can be converted to a
bool
. If the param is not found, returnsNone
unless required isTrue
.- Return type
- Raises
HTTPBadRequest – A required param is missing from the request, or can not be converted to a
bool
.
- get_param_as_date(name, format_string='%Y-%m-%d', required=False, store=None, default=None)[source]¶
Return the value of a query string parameter as a date.
- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘ids’).
- Keyword Arguments
format_string (str) – String used to parse the param value into a date. Any format recognized by strptime() is supported (default
"%Y-%m-%d"
).required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found and can be converted to a
date
according to the supplied format string. If the param is not found, returnsNone
unless required isTrue
.- Return type
- Raises
HTTPBadRequest – A required param is missing from the request, or the value could not be converted to a
date
.
- get_param_as_datetime(name, format_string='%Y-%m-%dT%H:%M:%SZ', required=False, store=None, default=None)[source]¶
Return the value of a query string parameter as a datetime.
- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘ids’).
- Keyword Arguments
format_string (str) – String used to parse the param value into a
datetime
. Any format recognized by strptime() is supported (default'%Y-%m-%dT%H:%M:%SZ'
).required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found and can be converted to a
datetime
according to the supplied format string. If the param is not found, returnsNone
unless required isTrue
.- Return type
- Raises
HTTPBadRequest – A required param is missing from the request, or the value could not be converted to a
datetime
.
- get_param_as_float(name, required=False, min_value=None, max_value=None, store=None, default=None)[source]¶
Return the value of a query string parameter as an float.
- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘limit’).
- Keyword Arguments
required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found or is not an float (defaultFalse
).min_value (float) – Set to the minimum value allowed for this param. If the param is found and it is less than min_value, an
HTTPError
is raised.max_value (float) – Set to the maximum value allowed for this param. If the param is found and its value is greater than max_value, an
HTTPError
is raised.store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found and can be converted to an
float
. If the param is not found, returnsNone
, unless required isTrue
.- Return type
- Raises
- HTTPBadRequest: The param was not found in the request, even though
it was required to be there, or it was found but could not be converted to an
float
. Also raised if the param’s value falls outside the given interval, i.e., the value must be in the interval: min_value <= value <= max_value to avoid triggering an error.
- get_param_as_int(name, required=False, min_value=None, max_value=None, store=None, default=None)[source]¶
Return the value of a query string parameter as an int.
- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘limit’).
- Keyword Arguments
required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found or is not an integer (defaultFalse
).min_value (int) – Set to the minimum value allowed for this param. If the param is found and it is less than min_value, an
HTTPError
is raised.max_value (int) – Set to the maximum value allowed for this param. If the param is found and its value is greater than max_value, an
HTTPError
is raised.store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found and can be converted to an
int
. If the param is not found, returnsNone
, unless required isTrue
.- Return type
- Raises
- HTTPBadRequest: The param was not found in the request, even though
it was required to be there, or it was found but could not be converted to an
int
. Also raised if the param’s value falls outside the given interval, i.e., the value must be in the interval: min_value <= value <= max_value to avoid triggering an error.
- get_param_as_json(name, required=False, store=None, default=None)[source]¶
Return the decoded JSON value of a query string parameter.
Given a JSON value, decode it to an appropriate Python type, (e.g.,
dict
,list
,str
,int
,bool
, etc.)Warning
If the
auto_parse_qs_csv
option is set toTrue
(defaultFalse
), the framework will misinterpret any JSON values that include literal (non-percent-encoded) commas. If the query string may include JSON, you can use JSON array syntax in lieu of CSV as a workaround.- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘payload’).
- Keyword Arguments
required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found. Otherwise, returns
None
unless required isTrue
.- Return type
- Raises
HTTPBadRequest – A required param is missing from the request, or the value could not be parsed as JSON.
- get_param_as_list(name, transform=None, required=False, store=None, default=None)[source]¶
Return the value of a query string parameter as a list.
List items must be comma-separated or must be provided as multiple instances of the same param in the query string ala application/x-www-form-urlencoded.
Note
To enable the interpretation of comma-separated parameter values, the
auto_parse_qs_csv
option must be set toTrue
(defaultFalse
).- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘ids’).
- Keyword Arguments
transform (callable) – An optional transform function that takes as input each element in the list as a
str
and outputs a transformed element for inclusion in the list that will be returned. For example, passingint
will transform list items into numbers.required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found. Otherwise, returns
None
unless required isTrue
.Empty list elements will be included by default, but this behavior can be configured by setting the
keep_blank_qs_values
option. For example, by default the following query strings would both result in['1', '', '3']
:things=1&things=&things=3 things=1,,3
Note, however, that for the second example string above to be interpreted as a list, the
auto_parse_qs_csv
option must be set toTrue
.- Return type
- Raises
HTTPBadRequest – A required param is missing from the request, or a transform function raised an instance of
ValueError
.
- get_param_as_uuid(name, required=False, store=None, default=None)[source]¶
Return the value of a query string parameter as an UUID.
The value to convert must conform to the standard UUID string representation per RFC 4122. For example, the following strings are all valid:
# Lowercase '64be949b-3433-4d36-a4a8-9f19d352fee8' # Uppercase 'BE71ECAA-F719-4D42-87FD-32613C2EEB60' # Mixed '81c8155C-D6de-443B-9495-39Fa8FB239b5'
- Parameters
name (str) – Parameter name, case-sensitive (e.g., ‘id’).
- Keyword Arguments
required (bool) – Set to
True
to raiseHTTPBadRequest
instead of returningNone
when the parameter is not found or is not a UUID (defaultFalse
).store (dict) – A
dict
-like object in which to place the value of the param, but only if the param is found (defaultNone
).default (any) – If the param is not found returns the given value instead of
None
- Returns
The value of the param if it is found and can be converted to a
UUID
. If the param is not found, returnsdefault
(defaultNone
), unless required isTrue
.- Return type
UUID
- Raises
- HTTPBadRequest: The param was not found in the request, even though
it was required to be there, or it was found but could not be converted to a
UUID
.
- class falcon.asgi.BoundedStream(receive, first_event=None, content_length=None)[source]¶
File-like input object for reading the body of the request, if any.
This class implements coroutine functions for asynchronous reading or iteration, but otherwise provides an interface similar to that defined by
io.IOBase
.If the request includes a Content-Length header, the number of bytes in the stream will be truncated to the length specified by the header. Otherwise, the stream will yield data until the ASGI server indicates that no more bytes are available.
For large request bodies, the preferred method of using the stream object is as an asynchronous iterator. In this mode, each body chunk is simply yielded in its entirety, as it is received from the ASGI server. Because no data is buffered by the framework, this is the most memory-efficient way of reading the request body:
# If the request body is empty or has already be consumed, the iteration # will immediately stop without yielding any data chunks. Otherwise, a # series of byte # strings will be yielded until the entire request # body has been yielded or the client disconnects. async for data_chunk in req.stream pass
The stream object also supports asynchronous
read()
andreadall()
methods:# Read all of the data at once; use only when you are confident # that the request body is small enough to not eat up all of # your memory. For small bodies, this is the most performant # option. data = await req.stream.readall() # ...or call read() without arguments data = await req.stream.read() # ...or read the data in chunks. You may choose to read more # or less than 32 KiB as shown in this example. But note that # this approach will generally be less efficient as compared # to async iteration, resulting in more usage and # copying of memory. while True: data_chunk = await req.stream.read(32 * 1024) if not data_chunk: break
Warning
Apps may not use both
read()
and the asynchronous iterator interface to consume the same request body; the only time that it is safe to do so is when one or the other method is used to completely read the entire body before the other method is even attempted. Therefore, it is important to always callexhaust()
orclose()
if a body has only been partially read and the remaining data is to be ignored.Note
The stream object provides a convenient abstraction over the series of body chunks contained in any ASGI “http.request” events received by the app. As such, some request body data may be temporarily buffered in memory during and between calls to read from the stream. The framework has been designed to minimize the amount of data that must be buffered in this manner.
- Parameters
receive (awaitable) – ASGI awaitable callable that will yield a new request event dictionary when one is available.
- Keyword Arguments
- close()[source]¶
Clear any buffered data and close this stream.
Once the stream is closed, any operation on it will raise an instance of
ValueError
.As a convenience, it is allowed to call this method more than once; only the first call, however, will have an effect.
- async read(size=None)[source]¶
Read some or all of the remaining bytes in the request body.
Warning
A size should always be specified, unless you can be certain that you have enough free memory for the entire request body, and that you have configured your web server to limit request bodies to a reasonable size (to guard against malicious requests).
Warning
Apps may not use both
read()
and the asynchronous iterator interface to consume the same request body; the only time that it is safe to do so is when one or the other method is used to completely read the entire body before the other method is even attempted. Therefore, it is important to always callexhaust()
orclose()
if a body has only been partially read and the remaining data is to be ignored.- Keyword Arguments
size (int) – The maximum number of bytes to read. The actual amount of data that can be read will depend on how much is available, and may be smaller than the amount requested. If the size is -1 or not specified, all remaining data is read and returned.
- Returns
The request body data, or
b''
if the body is empty or has already been consumed.- Return type
- async readall()[source]¶
Read and return all remaining data in the request body.
Warning
Only use this method when you can be certain that you have enough free memory for the entire request body, and that you have configured your web server to limit request bodies to a reasonable size (to guard against malicious requests).
- Returns
The request body data, or
b''
if the body is empty or has already been consumed.- Return type
Response¶
- class falcon.asgi.Response(options=None)[source]¶
Represents an HTTP response to a client request.
Note
Response
is not meant to be instantiated directly by responders.- Keyword Arguments
options (dict) – Set of global options passed from the App handler.
- status¶
HTTP status code or line (e.g.,
'200 OK'
). This may be set to a member ofhttp.HTTPStatus
, an HTTP status line string or byte string (e.g.,'200 OK'
), or anint
.Note
The Falcon framework itself provides a number of constants for common status codes. They all start with the
HTTP_
prefix, as in:falcon.HTTP_204
. (See also: Status Codes.)
- media¶
A serializable object supported by the media handlers configured via
falcon.RequestOptions
.Note
See also Media for more information regarding media handling.
- Type
- text¶
String representing response content.
Note
Falcon will encode the given text as UTF-8 in the response. If the content is already a byte string, use the
data
attribute instead (it’s faster).- Type
- data¶
Byte string representing response content.
Use this attribute in lieu of text when your content is already a byte string (of type
bytes
).Warning
Always use the text attribute for text, or encode it first to
bytes
when using the data attribute, to ensure Unicode characters are properly encoded in the HTTP response.- Type
- stream¶
An async iterator or generator that yields a series of byte strings that will be streamed to the ASGI server as a series of “http.response.body” events. Falcon will assume the body is complete when the iterable is exhausted or as soon as it yields
None
rather than an instance ofbytes
:async def producer(): while True: data_chunk = await read_data() if not data_chunk: break yield data_chunk resp.stream = producer
Alternatively, a file-like object may be used as long as it implements an awaitable
read()
method:resp.stream = await aiofiles.open('resp_data.bin', 'rb')
If the object assigned to
stream
holds any resources (such as a file handle) that must be explicitly released, the object must implement aclose()
method. Theclose()
method will be called after exhausting the iterable or file-like object.Note
In order to be compatible with Python 3.7+ and PEP 479, async iterators must return
None
instead of raisingStopIteration
. This requirement does not apply to async generators (PEP 525).Note
If the stream length is known in advance, you may wish to also set the Content-Length header on the response.
- sse¶
A Server-Sent Event (SSE) emitter, implemented as an async iterator or generator that yields a series of of
falcon.asgi.SSEvent
instances. Each event will be serialized and sent to the client as HTML5 Server-Sent Events:async def emitter(): while True: some_event = await get_next_event() if not some_event: # Send an event consisting of a single "ping" # comment to keep the connection alive. yield SSEvent() # Alternatively, one can simply yield None and # a "ping" will also be sent as above. # yield continue yield SSEvent(json=some_event, retry=5000) # ...or yield SSEvent(data=b'something', event_id=some_id) # Alternatively, you may yield anything that implements # a serialize() method that returns a byte string # conforming to the SSE event stream format. # yield some_event resp.sse = emitter()
Note
When the sse property is set, it supersedes both the text and data properties.
Note
When hosting an app that emits Server-Sent Events, the web server should be set with a relatively long keep-alive TTL to minimize the overhead of connection renegotiations.
- Type
coroutine
- context¶
Empty object to hold any data (in its attributes) about the response which is specific to your app (e.g. session object). Falcon itself will not interact with this attribute after it has been initialized.
Note
The preferred way to pass response-specific data, when using the default context type, is to set attributes directly on the context object. For example:
resp.context.cache_strategy = 'lru'
- Type
- context_type¶
Class variable that determines the factory or type to use for initializing the context attribute. By default, the framework will instantiate bare objects (instances of the bare
falcon.Context
class). However, you may override this behavior by creating a custom child class offalcon.asgi.Response
, and then passing that new class tofalcon.App()
by way of the latter’s response_type parameter.Note
When overriding context_type with a factory function (as opposed to a class), the function is called like a method of the current Response instance. Therefore the first argument is the Response instance itself (self).
- Type
class
- headers¶
Copy of all headers set for the response, sans cookies. Note that a new copy is created and returned each time this property is referenced.
- Type
- complete¶
Set to
True
from within a middleware method to signal to the framework that request processing should be short-circuited (see also Middleware).- Type
- property accept_ranges¶
Set the Accept-Ranges header.
The Accept-Ranges header field indicates to the client which range units are supported (e.g. “bytes”) for the target resource.
If range requests are not supported for the target resource, the header may be set to “none” to advise the client not to attempt any such requests.
Note
“none” is the literal string, not Python’s built-in
None
type.
- append_header(name, value)[source]¶
Set or append a header for this response.
If the header already exists, the new value will normally be appended to it, delimited by a comma. The notable exception to this rule is Set-Cookie, in which case a separate header line for each value will be included in the response.
Note
While this method can be used to efficiently append raw Set-Cookie headers to the response, you may find
set_cookie()
to be more convenient.
- append_link(target, rel, title=None, title_star=None, anchor=None, hreflang=None, type_hint=None, crossorigin=None)[source]¶
Append a link header to the response.
(See also: RFC 5988, Section 1)
Note
Calling this method repeatedly will cause each link to be appended to the Link header value, separated by commas.
Note
So-called “link-extension” elements, as defined by RFC 5988, are not yet supported. See also Issue #288.
- Parameters
target (str) – Target IRI for the resource identified by the link. Will be converted to a URI, if necessary, per RFC 3987, Section 3.1.
rel (str) –
Relation type of the link, such as “next” or “bookmark”.
(See also: http://www.iana.org/assignments/link-relations/link-relations.xhtml)
- Keyword Arguments
title (str) – Human-readable label for the destination of the link (default
None
). If the title includes non-ASCII characters, you will need to use title_star instead, or provide both a US-ASCII version using title and a Unicode version using title_star.title_star (tuple of str) –
Localized title describing the destination of the link (default
None
). The value must be a two-member tuple in the form of (language-tag, text), where language-tag is a standard language identifier as defined in RFC 5646, Section 2.1, and text is a Unicode string.Note
language-tag may be an empty string, in which case the client will assume the language from the general context of the current request.
Note
text will always be encoded as UTF-8.
anchor (str) – Override the context IRI with a different URI (default None). By default, the context IRI for the link is simply the IRI of the requested resource. The value provided may be a relative URI.
hreflang (str or iterable) – Either a single language-tag, or a
list
ortuple
of such tags to provide a hint to the client as to the language of the result of following the link. A list of tags may be given in order to indicate to the client that the target resource is available in multiple languages.type_hint (str) – Provides a hint as to the media type of the result of dereferencing the link (default
None
). As noted in RFC 5988, this is only a hint and does not override the Content-Type header returned when the link is followed.crossorigin (str) – Determines how cross origin requests are handled. Can take values ‘anonymous’ or ‘use-credentials’ or None. (See: https://www.w3.org/TR/html50/infrastructure.html#cors-settings-attribute)
- property cache_control¶
Set the Cache-Control header.
Used to set a list of cache directives to use as the value of the Cache-Control header. The list will be joined with “, ” to produce the value for the header.
- property content_length¶
Set the Content-Length header.
This property can be used for responding to HEAD requests when you aren’t actually providing the response body, or when streaming the response. If either the text property or the data property is set on the response, the framework will force Content-Length to be the length of the given text bytes. Therefore, it is only necessary to manually set the content length when those properties are not used.
Note
In cases where the response content is a stream (readable file-like object), Falcon will not supply a Content-Length header to the server unless content_length is explicitly set. Consequently, the server may choose to use chunked encoding in this case.
- property content_location¶
Set the Content-Location header.
This value will be URI encoded per RFC 3986. If the value that is being set is already URI encoded it should be decoded first or the header should be set manually using the set_header method.
- property content_range¶
A tuple to use in constructing a value for the Content-Range header.
The tuple has the form (start, end, length, [unit]), where start and end designate the range (inclusive), and length is the total length, or ‘*’ if unknown. You may pass
int
’s for these numbers (no need to convert tostr
beforehand). The optional value unit describes the range unit and defaults to ‘bytes’Note
You only need to use the alternate form, ‘bytes */1234’, for responses that use the status ‘416 Range Not Satisfiable’. In this case, raising
falcon.HTTPRangeNotSatisfiable
will do the right thing.(See also: RFC 7233, Section 4.2)
- property content_type¶
Sets the Content-Type header.
The
falcon
module provides a number of constants for common media types, includingfalcon.MEDIA_JSON
,falcon.MEDIA_MSGPACK
,falcon.MEDIA_YAML
,falcon.MEDIA_XML
,falcon.MEDIA_HTML
,falcon.MEDIA_JS
,falcon.MEDIA_TEXT
,falcon.MEDIA_JPEG
,falcon.MEDIA_PNG
, andfalcon.MEDIA_GIF
.
- delete_header(name)[source]¶
Delete a header that was previously set for this response.
If the header was not previously set, nothing is done (no error is raised). Otherwise, all values set for the header will be removed from the response.
Note that calling this method is equivalent to setting the corresponding header property (when said property is available) to
None
. For example:resp.etag = None
Warning
This method cannot be used with the Set-Cookie header. Instead, use
unset_cookie()
to remove a cookie and ensure that the user agent expires its own copy of the data as well.- Parameters
name (str) – Header name (case-insensitive). The name may contain only US-ASCII characters.
- Raises
ValueError – name cannot be
'Set-Cookie'
.
- property downloadable_as¶
Set the Content-Disposition header using the given filename.
The value will be used for the
filename
directive. For example, given'report.pdf'
, the Content-Disposition header would be set to:'attachment; filename="report.pdf"'
.As per RFC 6266 recommendations, non-ASCII filenames will be encoded using the
filename*
directive, whereasfilename
will contain the US ASCII fallback.
- property etag¶
Set the ETag header.
The ETag header will be wrapped with double quotes
"value"
in case the user didn’t pass it.
- property expires¶
Set the Expires header. Set to a
datetime
(UTC) instance.Note
Falcon will format the
datetime
as an HTTP date string.
- get_header(name, default=None)[source]¶
Retrieve the raw string value for the given header.
Normally, when a header has multiple values, they will be returned as a single, comma-delimited string. However, the Set-Cookie header does not support this format, and so attempting to retrieve it will raise an error.
- Parameters
name (str) – Header name, case-insensitive. Must be of type
str
orStringType
, and only character values 0x00 through 0xFF may be used on platforms that use wide characters.- Keyword Arguments
default – Value to return if the header is not found (default
None
).- Raises
ValueError – The value of the ‘Set-Cookie’ header(s) was requested.
- Returns
The value of the specified header if set, or the default value if not set.
- Return type
- property last_modified¶
Set the Last-Modified header. Set to a
datetime
(UTC) instance.Note
Falcon will format the
datetime
as an HTTP date string.
- property location¶
Set the Location header.
This value will be URI encoded per RFC 3986. If the value that is being set is already URI encoded it should be decoded first or the header should be set manually using the set_header method.
- async render_body()[source]¶
Get the raw bytestring content for the response body.
This coroutine can be awaited to get the raw data for the HTTP response body, taking into account the
text
,data
, andmedia
attributes.Note
This method ignores
stream
; the caller must check and handle that attribute directly.- Returns
The UTF-8 encoded value of the text attribute, if set. Otherwise, the value of the data attribute if set, or finally the serialized value of the media attribute. If none of these attributes are set,
None
is returned.- Return type
- property retry_after¶
Set the Retry-After header.
The expected value is an integral number of seconds to use as the value for the header. The HTTP-date syntax is not supported.
- schedule(callback)[source]¶
Schedule an async callback to run soon after sending the HTTP response.
This method can be used to execute a background job after the response has been returned to the client.
The callback is assumed to be an async coroutine function. It will be scheduled to run on the event loop as soon as possible.
The callback will be invoked without arguments. Use
functools.partial
to pass arguments to the callback as needed.Note
If an unhandled exception is raised while processing the request, the callback will not be scheduled to run.
Note
When an SSE emitter has been set on the response, the callback will be scheduled before the first call to the emitter.
Warning
Because coroutines run on the main request thread, care should be taken to ensure they are non-blocking. Long-running operations must use async libraries or delegate to an
Executor
pool to avoid blocking the processing of subsequent requests.- Parameters
callback (object) – An async coroutine function. The callback will be invoked without arguments.
- schedule_sync(callback)[source]¶
Schedule a synchronous callback to run soon after sending the HTTP response.
This method can be used to execute a background job after the response has been returned to the client.
The callback is assumed to be a synchronous (non-coroutine) function. It will be scheduled on the event loop’s default
Executor
(which can be overridden viaasyncio.AbstractEventLoop.set_default_executor()
).The callback will be invoked without arguments. Use
functools.partial
to pass arguments to the callback as needed.Note
If an unhandled exception is raised while processing the request, the callback will not be scheduled to run.
Note
When an SSE emitter has been set on the response, the callback will be scheduled before the first call to the emitter.
Warning
Synchronous callables run on the event loop’s default
Executor
, which uses an instance ofThreadPoolExecutor
unlessasyncio.AbstractEventLoop.set_default_executor()
is used to change it to something else. Due to the GIL, CPU-bound jobs will block request processing for the current process unless the defaultExecutor
is changed to one that is process-based instead of thread-based (e.g., an instance ofconcurrent.futures.ProcessPoolExecutor
).- Parameters
callback (object) – An async coroutine function or a synchronous callable. The callback will be called without arguments.
- set_cookie(name, value, expires=None, max_age=None, domain=None, path=None, secure=None, http_only=True, same_site=None)[source]¶
Set a response cookie.
Note
This method can be called multiple times to add one or more cookies to the response.
See also
To learn more about setting cookies, see Setting Cookies. The parameters listed below correspond to those defined in RFC 6265.
- Parameters
- Keyword Arguments
expires (datetime) –
Specifies when the cookie should expire. By default, cookies expire when the user agent exits.
(See also: RFC 6265, Section 4.1.2.1)
max_age (int) –
Defines the lifetime of the cookie in seconds. By default, cookies expire when the user agent exits. If both max_age and expires are set, the latter is ignored by the user agent.
Note
Coercion to
int
is attempted if provided withfloat
orstr
.(See also: RFC 6265, Section 4.1.2.2)
domain (str) –
Restricts the cookie to a specific domain and any subdomains of that domain. By default, the user agent will return the cookie only to the origin server. When overriding this default behavior, the specified domain must include the origin server. Otherwise, the user agent will reject the cookie.
Note
Cookies do not provide isolation by port, so the domain should not provide one. (See also: RFC 6265, Section 8.5)
(See also: RFC 6265, Section 4.1.2.3)
path (str) –
Scopes the cookie to the given path plus any subdirectories under that path (the “/” character is interpreted as a directory separator). If the cookie does not specify a path, the user agent defaults to the path component of the requested URI.
Warning
User agent interfaces do not always isolate cookies by path, and so this should not be considered an effective security measure.
(See also: RFC 6265, Section 4.1.2.4)
secure (bool) –
Direct the client to only return the cookie in subsequent requests if they are made over HTTPS (default:
True
). This prevents attackers from reading sensitive cookie data.Note
The default value for this argument is normally
True
, but can be modified by settingsecure_cookies_by_default
viaApp.resp_options
.Warning
For the secure cookie attribute to be effective, your application will need to enforce HTTPS.
(See also: RFC 6265, Section 4.1.2.5)
http_only (bool) –
The HttpOnly attribute limits the scope of the cookie to HTTP requests. In particular, the attribute instructs the user agent to omit the cookie when providing access to cookies via “non-HTTP” APIs. This is intended to mitigate some forms of cross-site scripting. (default:
True
)Note
HttpOnly cookies are not visible to javascript scripts in the browser. They are automatically sent to the server on javascript
XMLHttpRequest
orFetch
requests.(See also: RFC 6265, Section 4.1.2.6)
same_site (str) –
Helps protect against CSRF attacks by restricting when a cookie will be attached to the request by the user agent. When set to
'Strict'
, the cookie will only be sent along with “same-site” requests. If the value is'Lax'
, the cookie will be sent with same-site requests, and with “cross-site” top-level navigations. If the value is'None'
, the cookie will be sent with same-site and cross-site requests. Finally, when this attribute is not set on the cookie, the attribute will be treated as if it had been set to'None'
.(See also: Same-Site RFC Draft)
- Raises
KeyError – name is not a valid cookie name.
ValueError – value is not a valid cookie value.
- set_header(name, value)[source]¶
Set a header for this response to a given value.
Warning
Calling this method overwrites any values already set for this header. To append an additional value for this header, use
append_header()
instead.Warning
This method cannot be used to set cookies; instead, use
append_header()
orset_cookie()
.- Parameters
- Raises
ValueError – name cannot be
'Set-Cookie'
.
- set_headers(headers)[source]¶
Set several headers at once.
This method can be used to set a collection of raw header names and values all at once.
Warning
Calling this method overwrites any existing values for the given header. If a list containing multiple instances of the same header is provided, only the last value will be used. To add multiple values to the response for a given header, see
append_header()
.Warning
This method cannot be used to set cookies; instead, use
append_header()
orset_cookie()
.- Parameters
headers (Iterable[[str, str]]) –
An iterable of
[name, value]
two-member iterables, or a dict-like object that implements anitems()
method. Both name and value must be of typestr
and contain only US-ASCII characters.Note
Falcon can process an iterable of tuples slightly faster than a dict.
- Raises
ValueError – headers was not a
dict
orlist
oftuple
orIterable[[str, str]]
.
- set_stream(stream, content_length)[source]¶
Set both stream and content_length.
Although the
stream
andcontent_length
properties may be set directly, using this method ensurescontent_length
is not accidentally neglected when the length of the stream is known in advance. Using this method is also slightly more performant as compared to setting the properties individually.Note
If the stream length is unknown, you can set
stream
directly, and ignorecontent_length
. In this case, the ASGI server may choose to use chunked encoding for HTTP/1.1- Parameters
stream – A readable, awaitable file-like object or async iterable that returns byte strings. If the object implements a close() method, it will be called after reading all of the data.
content_length (int) – Length of the stream, used for the Content-Length header in the response.
- unset_cookie(name, domain=None, path=None)[source]¶
Unset a cookie in the response.
Clears the contents of the cookie, and instructs the user agent to immediately expire its own copy of the cookie.
Note
Modern browsers place restriction on cookies without the “same-site” cookie attribute set. To that end this attribute is set to
'Lax'
by this method.(See also: Same-Site warnings)
Warning
In order to successfully remove a cookie, both the path and the domain must match the values that were used when the cookie was created.
- Parameters
name (str) – Cookie name
- Keyword Arguments
domain (str) –
Restricts the cookie to a specific domain and any subdomains of that domain. By default, the user agent will return the cookie only to the origin server. When overriding this default behavior, the specified domain must include the origin server. Otherwise, the user agent will reject the cookie.
Note
Cookies do not provide isolation by port, so the domain should not provide one. (See also: RFC 6265, Section 8.5)
(See also: RFC 6265, Section 4.1.2.3)
path (str) –
Scopes the cookie to the given path plus any subdirectories under that path (the “/” character is interpreted as a directory separator). If the cookie does not specify a path, the user agent defaults to the path component of the requested URI.
Warning
User agent interfaces do not always isolate cookies by path, and so this should not be considered an effective security measure.
(See also: RFC 6265, Section 4.1.2.4)
- property vary¶
Value to use for the Vary header.
Set this property to an iterable of header names. For a single asterisk or field value, simply pass a single-element
list
ortuple
.The “Vary” header field in a response describes what parts of a request message, aside from the method, Host header field, and request target, might influence the origin server’s process for selecting and representing this response. The value consists of either a single asterisk (“*”) or a list of header field names (case-insensitive).
(See also: RFC 7231, Section 7.1.4)
- property viewable_as¶
Set an inline Content-Disposition header using the given filename.
The value will be used for the
filename
directive. For example, given'report.pdf'
, the Content-Disposition header would be set to:'inline; filename="report.pdf"'
.As per RFC 6266 recommendations, non-ASCII filenames will be encoded using the
filename*
directive, whereasfilename
will contain the US ASCII fallback.New in version 3.1.
- class falcon.asgi.SSEvent(data=None, text=None, json=None, event=None, event_id=None, retry=None, comment=None)[source]¶
Represents a Server-Sent Event (SSE).
Instances of this class can be yielded by an async generator in order to send a series of Server-Sent Events to the user agent.
(See also:
falcon.asgi.Response.sse
)- Keyword Arguments
data (bytes) – Raw byte string to use as the
data
field for the event message. Takes precedence over both text and json.text (str) – String to use for the
data
field in the message. Will be encoded as UTF-8 in the event. Takes precedence over json.json (object) – JSON-serializable object to be converted to JSON and used as the
data
field in the event message.event (str) – A string identifying the event type (AKA event name).
event_id (str) – The event ID that the User Agent should use for the EventSource object’s last event ID value.
retry (int) – The reconnection time to use when attempting to send the event. This must be an integer, specifying the reconnection time in milliseconds.
comment (str) – Comment to include in the event message; this is normally ignored by the user agent, but is useful when composing a periodic “ping” message to keep the connection alive. Since this is a common use case, a default “ping” comment will be included in any event that would otherwise be blank (i.e., one that does not specify any fields when initializing the SSEvent instance.)
- data¶
Raw byte string to use as the
data
field for the event message. Takes precedence over both text and json.- Type
- text¶
String to use for the
data
field in the message. Will be encoded as UTF-8 in the event. Takes precedence over json.- Type
- json¶
JSON-serializable object to be converted to JSON and used as the
data
field in the event message.- Type
- event_id¶
The event ID that the User Agent should use for the EventSource object’s last event ID value.
- Type
- retry¶
The reconnection time to use when attempting to send the event. This must be an integer, specifying the reconnection time in milliseconds.
- Type
- comment¶
Comment to include in the event message; this is normally ignored by the user agent, but is useful when composing a periodic “ping” message to keep the connection alive. Since this is a common use case, a default “ping” comment will be included in any event that would otherwise be blank (i.e., one that does not specify any of these fields when initializing the SSEvent instance.)
- Type
- serialize(handler=None)[source]¶
Serialize this event to string.
- Parameters
handler – Handler object that will be used to serialize the
json
attribute to string. When not provided, a default handler using the builtin JSON library will be used (defaultNone
).- Returns
string representation of this event.
- Return type