Utilities¶
URI Functions¶
-
falcon.util.uri.
decode
(encoded_uri)[source]¶ Decodes percent-encoded characters in a URI or query string.
This function models the behavior of urllib.parse.unquote_plus, but is faster. It is also more robust, in that it will decode escaped UTF-8 mutibyte sequences.
Parameters: encoded_uri (str) – An encoded URI (full or partial). Returns: - A decoded URL. Will be of type
unicode
on Python 2 IFF the - URL contained escaped non-ASCII characters, in which case UTF-8 is assumed per RFC 3986.
Return type: str - A decoded URL. Will be of type
-
falcon.util.uri.
encode
(uri)¶ Encodes a full or relative URI according to RFC 3986.
RFC 3986 defines a set of “unreserved” characters as well as a set of “reserved” characters used as delimiters. This function escapes all other “disallowed” characters by percent-encoding them.
Note
This utility is faster in the average case than the similar quote function found in
urlib
. It also strives to be easier to use by assuming a sensible default of allowed characters.Parameters: uri (str) – URI or part of a URI to encode. If this is a wide string (i.e., six.text_type
), it will be encoded to a UTF-8 byte array and any multibyte sequences will be percent-encoded as-is.Returns: - An escaped version of uri, where all disallowed characters
- have been percent-encoded.
Return type: str
-
falcon.util.uri.
encode_value
(uri)¶ Encodes a value string according to RFC 3986.
Disallowed characters are percent-encoded in a way that models
urllib.parse.quote(safe="~")
. However, the Falcon function is faster in the average case than the similar quote function found in urlib. It also strives to be easier to use by assuming a sensible default of allowed characters.All reserved characters are lumped together into a single set of “delimiters”, and everything in that set is escaped.
Note
RFC 3986 defines a set of “unreserved” characters as well as a set of “reserved” characters used as delimiters.
Parameters: uri (str) – URI fragment to encode. It is assumed not to cross delimiter boundaries, and so any reserved URI delimiter characters included in it will be escaped. If value is a wide string (i.e., six.text_type
), it will be encoded to a UTF-8 byte array and any multibyte sequences will be percent-encoded as-is.Returns: - An escaped version of uri, where all disallowed characters
- have been percent-encoded.
Return type: str
-
falcon.util.uri.
parse_host
(host, default_port=None)[source]¶ Parse a canonical ‘host:port’ string into parts.
Parse a host string (which may or may not contain a port) into parts, taking into account that the string may contain either a domain name or an IP address. In the latter case, both IPv4 and IPv6 addresses are supported.
Parameters: - host (str) – Host string to parse, optionally containing a port number.
- default_port (int, optional) – Port number to return when
the host string does not contain one (default
None
).
Returns: - A parsed (host, port) tuple from the given
host string, with the port converted to an
int
. If the host string does not specify a port, default_port is used instead.
Return type:
-
falcon.util.uri.
parse_query_string
(query_string, keep_blank_qs_values=False)[source]¶ Parse a query string into a dict.
Query string parameters are assumed to use standard form-encoding. Only parameters with values are parsed. for example, given ‘foo=bar&flag’, this function would ignore ‘flag’ unless the keep_blank_qs_values option is set.
Note
In addition to the standard HTML form-based method for specifying lists by repeating a given param multiple times, Falcon supports a more compact form in which the param may be given a single time but set to a
list
of comma-separated elements (e.g., ‘foo=a,b,c’).The two different ways of specifying lists may not be mixed in a single query string for the same parameter.
Parameters: Returns: - A dictionary of (name, value) pairs, one per query
parameter. Note that value may be a single
str
, or alist
ofstr
.
Return type: Raises: TypeError
– query_string was not astr
.
Testing¶
-
class
falcon.testing.
TestBase
(methodName='runTest')[source]¶ Extends
testtools.TestCase
to support WSGI integration testing.TestBase
provides a base class that provides some extra plumbing to help simulate WSGI calls without having to actually host your API in a server.Note
If
testtools
is not available,unittest
is used instead.-
api
¶ falcon.API – An API instance to target when simulating requests. Defaults to
falcon.API()
.
-
srmock
¶ falcon.testing.StartResponseMock – Provides a callable that simulates the behavior of the start_response argument that the server would normally pass into the WSGI app. The mock object captures various information from the app’s response to the simulated request.
-
test_route
¶ str – A simple, generated path that a test can use to add a route to the API.
-
simulate_request
(path, decode=None, **kwargs)[source]¶ Simulates a request to self.api.
Parameters: - path (str) – The path to request.
- decode (str, optional) – If this is set to a character encoding, such as ‘utf-8’, simulate_request will assume the response is a single byte string, and will decode it as the result of the request, rather than simply returning the standard WSGI iterable.
- kwargs (optional) – Same as those defined for falcon.testing.create_environ.
-
-
class
falcon.testing.
TestResource
[source]¶ Mock resource for integration testing.
This class implements the on_get responder, captures request data, and sets response body and headers.
Child classes may add additional methods and attributes as needed.
-
sample_status
¶ str – HTTP status to set in the response
-
sample_body
¶ str – Random body string to set in the response
-
resp_headers
¶ dict – Sample headers to use in the response
-
req
¶ falcon.Request – Request object passed into the on_get responder.
-
resp
¶ falcon.Response – Response object passed into the on_get responder.
-
kwargs
¶ dict – Keyword arguments passed into the on_get responder, if any.
-
called
¶ bool –
True
if on_get was ever called;False
otherwise.
-
-
class
falcon.testing.
StartResponseMock
[source]¶ Mock object representing a WSGI start_response callable.
-
call_count
¶ int – Number of times start_response was called.
-
status
¶ str – HTTP status line, e.g. ‘785 TPS Cover Sheet not attached’.
-
headers
¶ list – Raw headers list passed to start_response, per PEP-333.
-
headers_dict
¶ dict – Headers as a case-insensitive
dict
-like object, instead of alist
.
-
-
falcon.testing.
httpnow
()[source]¶ Returns the current UTC time as an RFC 1123 date.
Returns: An HTTP date string, e.g., “Tue, 15 Nov 1994 12:45:26 GMT”. Return type: str
-
falcon.testing.
rand_string
(min, max)[source]¶ Returns a randomly-generated string, of a random length.
Parameters:
-
falcon.testing.
create_environ
(path='/', query_string='', protocol='HTTP/1.1', scheme='http', host='falconframework.org', port=None, headers=None, app='', body='', method='GET', wsgierrors=None, file_wrapper=None)[source]¶ Creates a mock PEP-3333 environ
dict
for simulating WSGI requests.Parameters: - path (str, optional) – The path for the request (default ‘/’)
- query_string (str, optional) – The query string to simulate, without a leading ‘?’ (default ‘’)
- protocol (str, optional) – The HTTP protocol to simulate (default ‘HTTP/1.1’). If set to ‘HTTP/1.0’, the Host header will not be added to the environment.
- scheme (str) – URL scheme, either ‘http’ or ‘https’ (default ‘http’)
- host (str) – Hostname for the request (default ‘falconframework.org’)
- port (str or int, optional) – The TCP port to simulate. Defaults to the standard port used by the given scheme (i.e., 80 for ‘http’ and 443 for ‘https’).
- headers (dict or list, optional) – Headers as a
dict
or an iterable collection of (key, value)tuple
‘s - app (str) – Value for the
SCRIPT_NAME
environ variable, described in PEP-333: ‘The initial portion of the request URL’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.’ (default ‘’) - body (str or unicode) – The body of the request (default ‘’)
- method (str) – The HTTP method to use (default ‘GET’)
- wsgierrors (io) – The stream to use as wsgierrors
(default
sys.stderr
) - file_wrapper – Callable that returns an iterable, to be used as the value for wsgi.file_wrapper in the environ.
Miscellaneous¶
-
falcon.util.
deprecated
(instructions)[source]¶ Flags a method as deprecated.
This function returns a decorator which can be used to mark deprecated functions. Applying this decorator will result in a warning being emitted when the function is used.
Parameters: instructions (str) – Specific guidance for the developer, e.g.: ‘Please migrate to add_proxy(...)’‘
-
falcon.util.
dt_to_http
(dt)[source]¶ Converts a
datetime
instance to an HTTP date string.Parameters: dt (datetime) – A datetime
instance to convert, assumed to be UTC.Returns: An RFC 1123 date string, e.g.: “Tue, 15 Nov 1994 12:45:26 GMT”. Return type: str
-
falcon.util.
http_date_to_dt
(http_date)[source]¶ Converts an HTTP date string to a datetime instance.
Parameters: http_date (str) – An RFC 1123 date string, e.g.: “Tue, 15 Nov 1994 12:45:26 GMT”. Returns: - A UTC datetime instance corresponding to the given
- HTTP date.
Return type: datetime
-
falcon.util.
to_query_str
(params)[source]¶ Converts a dictionary of params to a query string.
Parameters: params (dict) – A dictionary of parameters, where each key is a parameter name, and each value is either a str
or something that can be converted into astr
. If params is alist
, it will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’)Returns: - A URI query string including the ‘?’ prefix, or an empty string
- if no params are given (the
dict
is empty).
Return type: str