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
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.
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
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.
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)¶
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.
- 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).
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.
- falcon.util.uri.parse_query_string(query_string, keep_blank_qs_values=False)¶
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.
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.
A dictionary of (name, value) pairs, one per query parameter. Note that value may be a single str, or a list of str.
TypeError – query_string was not a str.
- 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.
If testtools is not available, unittest is used instead.
An API instance to target when simulating requests. Defaults to falcon.API().
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.
A simple, generated path that a test can use to add a route to the API.
- simulate_request(path, decode=None, **kwargs)¶
Simulates a request to self.api.
- 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¶
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.
HTTP status to set in the response
Random body string to set in the response
Sample headers to use in the response
Request object passed into the on_get responder.
Response object passed into the on_get responder.
Keyword arguments passed into the on_get responder, if any.
True if on_get was ever called; False otherwise.
- on_get(req, resp, **kwargs)¶
Captures req, resp, and kwargs. Also sets up a sample response.
- 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.
Number of times start_response was called.
HTTP status line, e.g. ‘785 TPS Cover Sheet not attached’.
Raw headers list passed to start_response, per PEP-333.
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.
- 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.
- 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.
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(...)’‘
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
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
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
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.
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
Get the name of this timezone.
Parameters: dt (datetime.datetime) – Ignored Returns: “GMT” Return type: str