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
Request is 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. -
scheme
¶ str – Either ‘http’ or ‘https’.
-
protocol
¶ str – Deprecated alias for scheme. Will be removed in a future release.
-
method
¶ str – HTTP method requested (e.g., ‘GET’, ‘POST’, etc.)
-
host
¶ str – Hostname requested by the client
-
port
¶ int – Port used for the request. If the request URL does not specify a port, the default one for the given schema is returned (80 for HTTP and 443 for HTTPS).
-
netloc
¶ str – 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).
-
subdomain
¶ str – 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.
-
env
¶ dict – Reference to the WSGI environ
dict
passed in from the server. See also PEP-3333.
-
app
¶ str – Name of the WSGI app (if using WSGI’s notion of virtual hosting).
-
access_route
¶ list – 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:
Forwarded
X-Forwarded-For
X-Real-IP
If none of these headers are available, the value of
remote_addr
is 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.
-
remote_addr
¶ str – IP address of the closest client or proxy to the WSGI server.
This property is determined by the value of
REMOTE_ADDR
in 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_route
to retrieve the real IP address of the client.
-
context
¶ dict – Dictionary to hold any data 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.
-
context_type
¶ class – Class variable that determines the factory or type to use for initializing the context attribute. By default, the framework will instantiate standard
dict
objects. However, you may override this behavior by creating a custom child class offalcon.Request
, and then passing that new class to falcon.API() 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 (self).
-
uri
¶ str – The fully-qualified URI for the request.
-
url
¶ str – alias for uri.
-
relative_uri
¶ str – The path + query string portion of the full URI.
-
path
¶ str – Path portion of the request URL (not including query string).
Note
req.path may be set to a new value by a process_request() middleware method in order to influence routing.
-
query_string
¶ str – Query string portion of the request URL, without the preceding ‘?’ character.
-
uri_template
¶ str – 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 for process_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.
-
user_agent
¶ str – Value of the User-Agent header, or
None
if the header is missing.
-
accept
¶ str – Value of the Accept header, or ‘/‘ if the header is missing.
-
auth
¶ str – Value of the Authorization header, or
None
if the header is missing.
-
client_accepts_json
¶ bool –
True
if the Accept header indicates that the client is willing to receive JSON, otherwiseFalse
.
-
client_accepts_msgpack
¶ bool –
True
if the Accept header indicates that the client is willing to receive MessagePack, otherwiseFalse
.
-
client_accepts_xml
¶ bool –
True
if the Accept header indicates that the client is willing to receive XML, otherwiseFalse
.
-
content_type
¶ str – Value of the Content-Type header, or
None
if the header is missing.
-
content_length
¶ int – Value of the Content-Length header converted to an
int
, orNone
if the header is missing.
-
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_urlencoded
option is set, the framework will consume stream in 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 stream to normalize certain differences between the native input objects employed by different WSGI servers. In particular, bounded_stream is 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)
-
date
¶ datetime – Value of the Date header, converted to a
datetime
instance. The header value is assumed to conform to RFC 1123.
-
expect
¶ str – Value of the Expect header, or
None
if the header is missing.
-
range
¶ tuple of int – 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 continous ranges are supported (e.g., “bytes=0-0,-1” would result in an HTTPBadRequest exception when the attribute is accessed.)
-
range_unit
¶ str – Unit of the range parsed from the value of the Range header, or
None
if the header is missing
-
if_match
¶ str – Value of the If-Match header, or
None
if the header is missing.
-
if_none_match
¶ str – Value of the If-None-Match header, or
None
if the header is missing.
-
if_modified_since
¶ datetime – Value of the If-Modified-Since header, or
None
if the header is missing.
-
if_unmodified_since
¶ datetime – Value of the If-Unmodified-Since header, or
None
if the header is missing.
-
if_range
¶ str – Value of the If-Range header, or
None
if the header is missing.
-
headers
¶ dict – 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. This parsing can be costly, so unless you need all the headers in this format, you should use the get_header method or one of the convenience attributes instead, to get a value for a specific header.
-
params
¶ dict – 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.
dict – A dict of name/value cookie pairs. See also: Getting Cookies
-
options
¶ dict – Set of global options passed from the API handler.
-
client_accepts
(media_type)[source]¶ Determines whether or not the client accepts a given media type.
Parameters: media_type (str) – An Internet media type to check. Returns: True
if 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]¶ Returns 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: str
-
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: 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_urlencoded
toTrue
viaAPI.req_options
.If a key appears more than once in the form data, one of the values will be returned as a string, but it is undefined which one. Use req.get_param_as_list() to retrieve all the values.
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. Use req.get_param_as_list() to retrieve all the values.
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.- required (bool) – Set to
-
get_param_as_bool
(name, required=False, store=None, blank_as_true=False)[source]¶ Return the value of a query string parameter as a boolean
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
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) – If
True
, an empty string value will be treated asTrue
(defaultFalse
). Normally empty strings are ignored; if you would like to recognize such parameters, you must set the keep_blank_qs_values request option toTrue
. Request options are set globally for each instance offalcon.API
through the req_options attribute.
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.- required (bool) – Set to
-
get_param_as_date
(name, format_string='%Y-%m-%d', required=False, store=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
).
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.HTTPInvalidParam
– A transform function raised an instance ofValueError
.
- format_string (str) – String used to parse the param value
into a date. Any format recognized by strptime() is
supported (default
-
get_param_as_dict
(name, required=False, store=None)[source]¶ Return the value of a query string parameter as a dict.
Given a JSON value, parse and return it as a dict.
Parameters: name (str) – Parameter name, case-sensitive (e.g., ‘payload’).
Keyword Arguments: 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.HTTPInvalidParam
– The parameter’s value could not be parsed as JSON.
-
get_param_as_int
(name, required=False, min=None, max=None, store=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 (int) – Set to the minimum value allowed for this
param. If the param is found and it is less than min, an
HTTPError
is raised. - max (int) – Set to the maximum value allowed for this
param. If the param is found and its value is greater than
max, 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
).
Returns: The value of the param if it is found and can be converted to an integer. If the param is not found, returns
None
, unless required isTrue
.Return type: - Raises
- HTTPBadRequest: The param was not found in the request, even though
- it was required to be there. Also raised if the param’s value falls outside the given interval, i.e., the value must be in the interval: min <= value <= max to avoid triggering an error.
- required (bool) – Set to
-
get_param_as_list
(name, transform=None, required=False, store=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
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
).
Returns: The value of the param if it is found. Otherwise, returns
None
unless 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.HTTPInvalidParam
– A transform function raised an instance ofValueError
.
- transform (callable) – An optional transform function
that takes as input each element in the list as a
-
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 unicode
will be converted to UTF-8.
-
Response¶
-
class
falcon.
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 API handler. -
status
¶ str – 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
.
-
body
¶ str or unicode – String representing response content. If Unicode, Falcon will encode as UTF-8 in the response. If data is already a byte string, use the data attribute instead (it’s faster).
-
data
¶ bytes – Byte string representing response content.
Use this attribute in lieu of body when your content is already a byte string (
str
orbytes
in Python 2, or simplybytes
in Python 3). See also the note below.Note
Under Python 2.x, if your content is of type
str
, using the data attribute instead of body is the most efficient approach. However, if your text is of typeunicode
, you will need to use the body attribute instead.Under Python 3.x, on the other hand, the 2.x
str
type can be thought of as having been replaced by what was once theunicode
type, and so you will need to always use the body attribute for strings to ensure Unicode characters are properly encoded in the HTTP response.
-
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.
-
stream_len
¶ int – Expected length of stream. If stream is set, but stream_len is not, Falcon will not supply a Content-Length header to the WSGI server. Consequently, the server may choose to use chunked encoding or one of the other strategies suggested by PEP-3333.
-
context
¶ dict – 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.
-
context_type
¶ class – Class variable that determines the factory or type to use for initializing the context attribute. By default, the framework will instantiate standard
dict
objects. However, you may override this behavior by creating a custom child class offalcon.Response
, and then passing that new class to falcon.API() 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).
-
options
¶ dict – Set of global options passed from the API handler.
-
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.
-
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: https://tools.ietf.org/html/rfc5988
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://goo.gl/618GHr for a list of registered link relation types.
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. If the string contains non-ASCII characters, it should be passed as a
unicode
type 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
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.
-
append_header
(name, value)[source]¶ Set or append a header for this response.
Warning
If the header already exists, the new value will be appended to it, delimited by a comma. Most header specifications support this format, Set-Cookie being the notable exceptions.
Warning
For setting cookies, see
set_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 of type
str
orStringType
and contain only US-ASCII characters. Under Python 2.x, theunicode
type 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_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 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: http://goo.gl/Iglhp
-
content_type
¶ Set the Content-Type header.
-
delete_header
(name)[source]¶ Delete a header for this response.
If the header was not previously set, do nothing.
Parameters: name (str) – Header name (case-insensitive). Must be of type str
orStringType
and contain only US-ASCII characters. Under Python 2.x, theunicode
type is also accepted, although such strings are also limited to US-ASCII.
-
etag
¶ Set the ETag header.
-
get_header
(name)[source]¶ Retrieve the raw string value for the given header.
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.Returns: The header’s value if set, otherwise None
.Return type: str
-
last_modified
¶ Set the Last-Modified header. Set to a
datetime
(UTC) instance.Note
Falcon will format the
datetime
as 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_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.
(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
viaAPI.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) –
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
– name is not a valid cookie name.ValueError
– value is 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 the existing value, if any.
Warning
For setting cookies, see instead
set_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 of type
str
orStringType
and contain only US-ASCII characters. Under Python 2.x, theunicode
type is also accepted, although such strings are also limited to US-ASCII.
-
set_headers
(headers)[source]¶ Set several headers at once.
Warning
Calling this method overwrites existing values, if any.
Parameters: headers (dict or list) – A dictionary of header names and values to set, or a
list
of (name, value) tuples. Both name and value must be of typestr
orStringType
and contain only US-ASCII characters. Under Python 2.x, theunicode
type 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
– headers was not adict
orlist
oftuple
.
-
set_stream
(stream, stream_len)[source]¶ Convenience method for setting both stream and stream_len.
Although the stream and stream_len properties may be set directly, using this method ensures stream_len is not accidentally neglected when the length of the stream is known in advance.
Note
If the stream length is unknown, you can set stream directly, and ignore stream_len. In this case, the WSGI 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
list
ortuple
.“Tells downstream proxies how to match future request headers to decide whether the cached response can be used rather than requesting a fresh one from the origin server.”
(Wikipedia)
See also: http://goo.gl/NGHdL
-