Request & Response
Instances of the Request and Response classes are passed into responders as the second and third arguments, respectively.
import falcon
class Resource(object):
def on_get(self, req, resp):
resp.body = '{"message": "Hello world!"}'
resp.status = falcon.HTTP_200
Request
-
class falcon.Request(env, options=None)[source] -
Represents a client’s HTTP request.
Note
Requestis not meant to be instantiated directly by responders.Parameters: env (dict) – A WSGI environment dict passed in from the server. See also PEP-3333. Keyword Arguments: options (dict) – Set of global options passed from the API handler. -
env -
Reference to the WSGI environ
dictpassed in from the server. (See also PEP-3333.)Type: dict
-
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
New in 2.0: the default
context_type(see below) was changed from dict to a bare class, and the preferred way to pass request-specific data is now to set attributes directly on thecontextobject, for example:req.context.role = 'trial' req.context.user = 'guest'
Type: object
-
context_type -
Class variable that determines the factory or type to use for initializing the
contextattribute. By default, the framework will instantiate bare objects (instances of the barefalcon.Contextclass). However, you may override this behavior by creating a custom child class offalcon.Request, and then passing that new class tofalcon.API()by way of the latter’srequest_typeparameter.Note
When overriding
context_typewith 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 (self).Type: class
-
scheme -
URL scheme used for the request. Either ‘http’ or ‘https’.
Note
If the request was proxied, the scheme may not match what was originally requested by the client.
forwarded_schemecan be used, instead, to handle such cases.Type: str
-
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:
ForwardedX-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
schemeis returned instead.(See also: RFC 7239, Section 1)
Type: str
-
method -
HTTP method requested (e.g., ‘GET’, ‘POST’, etc.)
Type: str
-
host -
Host request header field
Type: str
-
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:
ForwardedX-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
hostis 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
hostis sufficient.(See also: RFC 7239, Section 4)
Type: str
-
port -
Port used for the request. If the request URI does not specify a port, the default one for the given schema is returned (80 for HTTP and 443 for HTTPS).
Type: int
-
netloc -
Returns the ‘host:port’ portion of the request URL. The port may be ommitted if it is the default one for the URL’s schema (80 for HTTP and 443 for HTTPS).
Type: str
-
subdomain -
Leftmost (i.e., most specific) subdomain from the hostname. If only a single domain name is given,
subdomainwill beNone.Note
If the hostname in the request is an IP address, the value for
subdomainis undefined.Type: str
-
app -
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 “SCRIPT_NAME” environ variable defined by PEP-3333.)
Type: str
-
uri -
The fully-qualified URI for the request.
Type: str
-
url -
Alias for
uri.Type: str
-
forwarded_uri -
Original URI for proxied requests. Uses
forwarded_schemeandforwarded_hostin order to reconstruct the original URI requested by the user agent.Type: str
-
relative_uri -
The path and query string portion of the request URI, omitting the scheme and host.
Type: str
-
prefix -
The prefix of the request URI, including scheme, host, and WSGI app (if any).
Type: str
-
forwarded_prefix -
The prefix of the original URI for proxied requests. Uses
forwarded_schemeandforwarded_hostin order to reconstruct the original URI.Type: str
-
path -
Path portion of the request URI (not including query string).
Note
req.pathmay 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. 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.Type: str
-
query_string -
Query string portion of the request URI, without the preceding ‘?’ character.
Type: str
-
uri_template -
The template for the route that was matched for this request. May be
Noneif the request has not yet been routed, as would be the case forprocess_request()middleware methods. May also beNoneif your app uses a custom routing engine and the engine does not provide the URI template when resolving a route.Type: str
-
remote_addr -
IP address of the closest client or proxy to the WSGI server.
This property is determined by the value of
REMOTE_ADDRin the WSGI environment dict. Since this address is not derived from an HTTP header, clients and proxies can not forge it.Note
If your application is behind one or more reverse proxies, you can use
access_routeto retrieve the real IP address of the client.Type: str
-
access_route -
IP address of the original client, as well as any known addresses of proxies fronting the WSGI server.
The following request headers are checked, in order of preference, to determine the addresses:
ForwardedX-Forwarded-ForX-Real-IP
If none of these headers are available, the value of
remote_addris used instead.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: list
-
forwarded -
Value of the Forwarded header, as a parsed list of
falcon.Forwardedobjects, orNoneif 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: list
-
date -
Value of the Date header, converted to a
datetimeinstance. The header value is assumed to conform to RFC 1123.Type: datetime
-
auth -
Value of the Authorization header, or
Noneif the header is missing.Type: str
-
user_agent -
Value of the User-Agent header, or
Noneif the header is missing.Type: str
-
referer -
Value of the Referer header, or
Noneif the header is missing.Type: str
-
accept -
Value of the Accept header, or ‘/’ if the header is missing.
Type: str
-
client_accepts_json -
Trueif the Accept header indicates that the client is willing to receive JSON, otherwiseFalse.Type: bool
-
client_accepts_msgpack -
Trueif the Accept header indicates that the client is willing to receive MessagePack, otherwiseFalse.Type: bool
-
client_accepts_xml -
Trueif the Accept header indicates that the client is willing to receive XML, otherwiseFalse.Type: bool
-
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: dict
-
content_type -
Value of the Content-Type header, or
Noneif the header is missing.Type: str
-
content_length -
Value of the Content-Length header converted to an
int, orNoneif the header is missing.Type: int
-
stream -
File-like input object for reading the body of the request, if any. This object provides direct access to the server’s data stream and is non-seekable. In order to avoid unintended side effects, and to provide maximum flexibility to the application, Falcon itself does not buffer or spool the data in any way.
Since this object is provided by the WSGI server itself, rather than by Falcon, it may behave differently depending on how you host your app. For example, attempting to read more bytes than are expected (as determined by the Content-Length header) may or may not block indefinitely. It’s a good idea to test your WSGI server to find out how it behaves.
This can be particulary problematic when a request body is expected, but none is given. In this case, the following call blocks under certain WSGI servers:
# Blocks if Content-Length is 0 data = req.stream.read()
The workaround is fairly straightforward, if verbose:
# If Content-Length happens to be 0, or the header is # missing altogether, this will not block. data = req.stream.read(req.content_length or 0)
Alternatively, when passing the stream directly to a consumer, it may be necessary to branch off the value of the Content-Length header:
if req.content_length: doc = json.load(req.stream)For a slight performance cost, you may instead wish to use
bounded_stream, which wraps the native WSGI input object to normalize its behavior.Note
If an HTML form is POSTed to the API using the application/x-www-form-urlencoded media type, and the
auto_parse_form_urlencodedoption is set, the framework will consumestreamin order to parse the parameters and merge them into the query string parameters. In this case, the stream will be left at EOF.
-
bounded_stream -
File-like wrapper around
streamto normalize certain differences between the native input objects employed by different WSGI servers. In particular,bounded_streamis aware of the expected Content-Length of the body, and will never block on out-of-bounds reads, assuming the client does not stall while transmitting the data to the server.For example, the following will not block when Content-Length is 0 or the header is missing altogether:
data = req.bounded_stream.read()
This is also safe:
doc = json.load(req.bounded_stream)
-
expect -
Value of the Expect header, or
Noneif the header is missing.Type: str
-
media -
Returns a deserialized form of the request stream. When called, it will attempt to deserialize the request stream using the Content-Type header as well as the media-type handlers configured via
falcon.RequestOptions.See Media for more information regarding media handling.
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.
Type: object
-
range -
A 2-member
tupleparsed 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 continous 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
Noneif the header is missingType: str
-
if_match -
Value of the If-Match header, as a parsed list of
falcon.ETagobjects orNoneif the header is missing or its value is blank.This property provides a list of all
entity-tagsin the header, both strong and weak, in the same order as listed in the header.(See also: RFC 7232, Section 3.1)
Type: list
-
if_none_match -
Value of the If-None-Match header, as a parsed list of
falcon.ETagobjects orNoneif the header is missing or its value is blank.This property provides a list of all
entity-tagsin the header, both strong and weak, in the same order as listed in the header.(See also: RFC 7232, Section 3.2)
Type: list
-
if_modified_since -
Value of the If-Modified-Since header, or
Noneif the header is missing.Type: datetime
-
if_unmodified_since -
Value of the If-Unmodified-Since header, or
Noneif the header is missing.Type: datetime
-
if_range -
Value of the If-Range header, or
Noneif the header is missing.Type: str
-
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: dict
-
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: dict
-
options -
Set of global options passed from the API handler.
Type: dict
-
client_accepts(media_type)[source] -
Determine whether or not the client accepts a given media type.
Parameters: media_type (str) – An Internet media type to check. Returns: Trueif the client has indicated in the Accept header that it accepts the specified media type. Otherwise, returnsFalse.Return type: bool
-
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 Noneif the client does not accept any of the given types.Return type: str
-
context_type -
alias of
falcon.util.structures.Context
-
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 Noneif 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: list
-
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
Noneif 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.
-
-
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 and merge them into the query string parameters. To enable this functionality, set
auto_parse_form_urlencodedtoTrueviaAPI.req_options.Note
Similar to the way multiple keys in form data is handled, if a query parameter is assigned a comma-separated list of values (e.g.,
foo=a,b,c), only one of those values will be returned, and it is undefined which one. Useget_param_as_list()to retrieve all the values.Parameters: name (str) – Parameter name, case-sensitive (e.g., ‘sort’).
Keyword Arguments: -
required (bool) – Set to
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
Noneif param is not found and is not required.Return type: Raises: HTTPBadRequest– A required param is missing from the request. -
required (bool) – Set to
-
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,
Trueis assumed and returned. If the parameter is missing altogether,Noneis 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', 'yes', '1', 'on') FALSE_STRINGS = ('false', 'False', 'no', '0', 'off')Parameters: name (str) – Parameter name, case-sensitive (e.g., ‘detailed’).
Keyword Arguments: -
required (bool) – Set to
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
Truebeing returned when such a parameter is present, andFalseotherwise. To require the client to explicitly opt-in to a truthy value, passblank_as_true=Falseto returnFalsewhen 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, returnsNoneunlessrequiredisTrue.Return type: Raises: HTTPBadRequest– A required param is missing from the request, or can not be converted to abool. -
required (bool) – Set to
-
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
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
dateaccording to the supplied format string. If the param is not found, returnsNoneunless required isTrue.Return type: Raises: HTTPBadRequest– A required param is missing from the request, or the value could not be converted to adate. -
format_string (str) – String used to parse the param value into a date. Any format recognized by strptime() is supported (default
-
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
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
datetimeaccording to the supplied format string. If the param is not found, returnsNoneunless required isTrue.Return type: Raises: HTTPBadRequest– A required param is missing from the request, or the value could not be converted to adatetime. -
format_string (str) – String used to parse the param value into a
-
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
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
HTTPErroris 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
HTTPErroris 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, unlessrequiredisTrue.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.
-
required (bool) – Set to
-
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
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
HTTPErroris 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
HTTPErroris 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, unlessrequiredisTrue.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.
-
required (bool) – Set to
-
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.)Parameters: name (str) – Parameter name, case-sensitive (e.g., ‘payload’).
Keyword Arguments: -
required (bool) – Set to
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
Noneunless required isTrue.Return type: Raises: HTTPBadRequest– A required param is missing from the request, or the value could not be parsed as JSON. -
required (bool) – Set to
-
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.
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
strand outputs a transformed element for inclusion in the list that will be returned. For example, passingintwill transform list items into numbers. -
required (bool) – Set to
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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
Noneunless required is True. Empty list elements will be discarded. For example, the following query strings would both result in[‘1’, ‘3’]:things=1,,3 things=1&things=&things=3
Return type: Raises: HTTPBadRequest– A required param is missing from the request, or a transform function raised an instance ofValueError. -
transform (callable) – An optional transform function that takes as input each element in the list as a
-
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
Trueto raiseHTTPBadRequestinstead of returningNonewhen 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), unlessrequiredisTrue.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.
-
required (bool) – Set to
-
has_param(name)[source] -
Determine whether or not the query string parameter already exists.
Parameters: name (str) – Parameter name, case-sensitive (e.g., ‘sort’). Returns: Trueif param is found, orFalseif param is not found.Return type: bool
-
log_error(message)[source] -
Write an error message to the server’s log.
Prepends timestamp and request info to message, and writes the result out to the WSGI server’s error stream (
wsgi.error).Parameters: message (str or unicode) – Description of the problem. On Python 2, instances of unicodewill be converted to UTF-8.
-
-
class falcon.Forwarded[source] -
Represents a parsed Forwarded header.
(See also: RFC 7239, Section 4)
-
src -
The value of the “for” parameter, or
Noneif the parameter is absent. Identifies the node making the request to the proxy.Type: str
-
dest -
The value of the “by” parameter, or
Noneif the parameter is absent. Identifies the client-facing interface of the proxy.Type: str
-
host -
The value of the “host” parameter, or
Noneif the parameter is absent. Provides the host request header field as received by the proxy.Type: str
-
scheme -
The value of the “proto” parameter, or
Noneif the parameter is absent. Indicates the protocol that was used to make the request to the proxy.Type: str
-
Response
-
class falcon.Response(options=None)[source] -
Represents an HTTP response to a client request.
Note
Responseis not meant to be instantiated directly by responders.Keyword Arguments: options (dict) – Set of global options passed from the API handler. -
status -
HTTP status line (e.g., ‘200 OK’). Falcon requires the full status line, not just the code (e.g., 200). This design makes the framework more efficient because it does not have to do any kind of conversion or lookup when composing the WSGI response.
If not set explicitly, the status defaults to ‘200 OK’.
Note
Falcon provides a number of constants for common status codes. They all start with the
HTTP_prefix, as in:falcon.HTTP_204.Type: str
-
media -
A serializable object supported by the media handlers configured via
falcon.RequestOptions.See Media for more information regarding media handling.
Type: object
-
body -
String representing response content.
If set to a Unicode type (
unicodein Python 2, orstrin Python 3), Falcon will encode the text as UTF-8 in the response. If the content is already a byte string, use thedataattribute instead (it’s faster).Type: str or unicode
-
data -
Byte string representing response content.
Use this attribute in lieu of
bodywhen your content is already a byte string (strorbytesin Python 2, or simplybytesin Python 3). See also the note below.Note
Under Python 2.x, if your content is of type
str, using thedataattribute instead ofbodyis the most efficient approach. However, if your text is of typeunicode, you will need to use thebodyattribute instead.Under Python 3.x, on the other hand, the 2.x
strtype can be thought of as having been replaced by what was once theunicodetype, and so you will need to always use thebodyattribute for strings to ensure Unicode characters are properly encoded in the HTTP response.Type: bytes
-
stream -
Either a file-like object with a
read()method that takes an optional size argument and returns a block of bytes, or an iterable object, representing response content, and yielding blocks as byte strings. Falcon will use wsgi.file_wrapper, if provided by the WSGI server, in order to efficiently serve file-like objects.Note
If the stream is set to an iterable object that requires resource cleanup, it can implement a close() method to do so. The close() method will be called upon completion of the request.
-
stream_len -
Deprecated alias for
content_length.Type: int
-
context -
Dictionary to hold any data about the response which is specific to your app. Falcon itself will not interact with this attribute after it has been initialized.
Type: dict
-
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
New in 2.0: the default
context_type(see below) was changed from dict to a bare class, and the preferred way to pass response-specific data is now to set attributes directly on thecontextobject, for example:resp.context.cache_strategy = 'lru'
Type: object
-
context_type -
Class variable that determines the factory or type to use for initializing the
contextattribute. By default, the framework will instantiate bare objects (instances of the barefalcon.Contextclass). However, you may override this behavior by creating a custom child class offalcon.Response, and then passing that new class tofalcon.API()by way of the latter’sresponse_typeparameter.Note
When overriding
context_typewith 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
-
options -
Set of global options passed from the API handler.
Type: dict
-
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: dict
-
complete -
Set to
Truefrom within a middleware method to signal to the framework that request processing should be short-circuited (see also Middleware).Type: bool
-
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
Nonetype.
-
add_link(target, rel, title=None, title_star=None, anchor=None, hreflang=None, type_hint=None)[source] -
Add 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 usetitle_starinstead, or provide both a US-ASCII version usingtitleand a Unicode version usingtitle_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. If the string contains non-ASCII characters, it should be passed as a
unicodetype string (requires the ‘u’ prefix in Python 2). - 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
listortupleof 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.
-
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.Parameters: - name (str) – Header name (case-insensitive). The restrictions noted below for the header’s value also apply here.
-
value (str) – Value for the header. Must be convertable to
stror be of typestrorStringType. Strings must contain only US-ASCII characters. Under Python 2.x, theunicodetype is also accepted, although such strings are also limited to US-ASCII.
-
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.
-
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
bodyproperty or thedataproperty is set on the response, the framework will force Content-Length to be the length of the given body 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 WSGI server unless
content_lengthis explicitly set. Consequently, the server may choose to use chunked encoding or one of the other strategies suggested by PEP-3333.
-
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.
-
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 tostrbeforehand). 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.HTTPRangeNotSatisfiablewill do the right thing.(See also: RFC 7233, Section 4.2)
-
content_type -
Sets the Content-Type header.
The
falconmodule 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.
-
context_type -
alias of
falcon.util.structures.Context
-
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). Must be of type strorStringTypeand contain only US-ASCII characters. Under Python 2.x, theunicodetype is also accepted, although such strings are also limited to US-ASCII.Raises: ValueError–namecannot be'Set-Cookie'.
-
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"'.
-
etag -
Set the ETag header.
The ETag header will be wrapped with double quotes
"value"in case the user didn’t pass it.
-
expires -
Set the Expires header. Set to a
datetime(UTC) instance.Note
Falcon will format the
datetimeas 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 strorStringType, 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: str
-
last_modified -
Set the Last-Modified header. Set to a
datetime(UTC) instance.Note
Falcon will format the
datetimeas an HTTP date string.
-
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.
-
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.
-
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_ageandexpiresare set, the latter is ignored by the user agent.Note
Coercion to
intis attempted if provided withfloatorstr.(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.
(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_defaultviaAPI.resp_options.Warning
For the
securecookie attribute to be effective, your application will need to enforce HTTPS.(See also: RFC 6265, Section 4.1.2.5)
-
http_only (bool) –
Direct the client to only transfer the cookie with unscripted HTTP requests (default:
True). This is intended to mitigate some forms of cross-site scripting.(See also: RFC 6265, Section 4.1.2.6)
Raises: -
KeyError–nameis not a valid cookie name. -
ValueError–valueis not a valid cookie value.
-
expires (datetime) –
-
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: - name (str) – Header name (case-insensitive). The restrictions noted below for the header’s value also apply here.
-
value (str) – Value for the header. Must be convertable to
stror be of typestrorStringType. Strings must contain only US-ASCII characters. Under Python 2.x, theunicodetype is also accepted, although such strings are also limited to US-ASCII.
Raises: ValueError–namecannot 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 (dict or list) – A dictionary of header names and values to set, or a
listof (name, value) tuples. Both name and value must be of typestrorStringTypeand contain only US-ASCII characters. Under Python 2.x, theunicodetype is also accepted, although such strings are also limited to US-ASCII.Note
Falcon can process a list of tuples slightly faster than a dict.
Raises: ValueError–headerswas not adictorlistoftuple.
-
set_stream(stream, content_length)[source] -
Convenience method for setting both
streamandcontent_length.Although the
streamandcontent_lengthproperties may be set directly, using this method ensurescontent_lengthis 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
streamdirectly, and ignorecontent_length. In this case, the WSGI server may choose to use chunked encoding or one of the other strategies suggested by PEP-3333.Parameters: - stream – A readable file-like object.
- content_length (int) – Length of the stream, used for the Content-Length header in the response.
-
stream_len -
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
bodyproperty or thedataproperty is set on the response, the framework will force Content-Length to be the length of the given body 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 WSGI server unless
content_lengthis explicitly set. Consequently, the server may choose to use chunked encoding or one of the other strategies suggested by PEP-3333.
-
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.
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.
-
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
listortuple.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)
-
© 2019 by Falcon contributors
Licensed under the Apache License, Version 2.0.
https://falcon.readthedocs.io/en/2.0.0/api/request_and_response.html