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
- 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: tuple
- 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’).
When using this format, all commas uri-encoded will not be treated by Falcon as a delimiter. If the client wants to send a value as a list, it must not encode the commas with the values.
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 a list of str.
Return type: dict
Raises: TypeError – query_string was not a str.
Testing¶
- class falcon.testing.TestBase(methodName='runTest')¶
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.
- setUp()¶
Initializer, unittest-style
- simulate_request(path, decode=None, **kwargs)¶
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.
- tearDown()¶
Destructor, unittest-style
- class falcon.testing.TestResource¶
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.
- on_get(req, resp, **kwargs)¶
GET responder.
Captures req, resp, and kwargs. Also sets up a sample response.
Parameters: - req – Falcon Request instance.
- resp – Falcon Response instance.
- kwargs – URI template name=value pairs, if any, along with any extra args injected by middleware.
- class falcon.testing.StartResponseMock¶
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 a list.
- __call__(status, headers, exc_info=None)¶
Implements the PEP-3333 start_response protocol.
- falcon.testing.rand_string(min, max)¶
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)¶
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.deprecated(instructions)¶
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.http_now()¶
Returns the current UTC time as an IMF-fixdate.
Returns: The current UTC time as an IMF-fixdate, e.g., ‘Tue, 15 Nov 1994 12:45:26 GMT’. Return type: str
- falcon.dt_to_http(dt)¶
Converts a datetime instance to an HTTP date string.
Parameters: dt (datetime) – A datetime instance to convert, assumed to be UTC. Returns: 26 GMT”. Return type: str: An RFC 1123 date string, e.g.: “Tue, 15 Nov 1994 12:45
- falcon.http_date_to_dt(http_date)¶
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.to_query_str(params)¶
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 a str. If params is a list, 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
- class falcon.util.TimezoneGMT¶
GMT timezone class implementing the datetime.tzinfo interface.
- dst(dt)¶
Return the daylight saving time (DST) adjustment.
Parameters: dt (datetime.datetime) – Ignored Returns: DST adjustment for GMT, which is always 0. Return type: datetime.timedelta
- tzname(dt)¶
Get the name of this timezone.
Parameters: dt (datetime.datetime) – Ignored Returns: “GMT” Return type: str
- utcoffset(dt)¶
Get the offset from UTC.
Parameters: dt (datetime.datetime) – Ignored Returns: GMT offset, which is equivalent to UTC and so is aways 0. Return type: datetime.timedelta