URI utilities.
This module provides utility functions to parse, encode, decode, and otherwise manipulate a URI. These functions are not available directly in the falcon
module, and so must be explicitly imported:
from falcon import uri name, port = uri.parse_host('example.org:8080')
falcon.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., compat.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.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., compat.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.uri.decode(encoded_uri, unquote_plus=True)
[source]
Decodes percent-encoded characters in a URI or query string.
This function models the behavior of urllib.parse.unquote_plus
, albeit in a faster, more straightforward manner.
Parameters: | encoded_uri (str) – An encoded URI (full or partial). |
---|---|
Keyword Arguments: | |
unquote_plus (bool) – Set to False to retain any plus (‘+’) characters in the given string, rather than converting them to spaces (default True ). Typically you should set this to False when decoding any part of a URI other than the query string. | |
Returns: | A decoded URL. If the URL contains escaped non-ASCII characters, UTF-8 is assumed per RFC 3986. |
Return type: | str |
falcon.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. |
---|---|
Keyword Arguments: | |
default_port (int) – 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.uri.parse_query_string(query_string, keep_blank=False, csv=True)
[source]
Parse a query string into a dict.
Query string parameters are assumed to use standard form-encoding. Only parameters with values are returned. 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 |
Return type: | |
Raises: |
|
falcon.uri.unquote_string(quoted)
[source]
Unquote an RFC 7320 “quoted-string”.
Parameters: | quoted (str) – Original quoted string |
---|---|
Returns: | unquoted string |
Return type: | str |
Raises: |
TypeError – quoted was not a str . |
falcon.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.http_now()
[source]
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)
[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.http_date_to_dt(http_date, obs_date=False)
[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”. |
---|---|
Keyword Arguments: | |
obs_date (bool) – Support obs-date formats according to RFC 7231, e.g.: “Sunday, 06-Nov-94 08:49:37 GMT” (default False ). | |
Returns: | A UTC datetime instance corresponding to the given HTTP date. |
Return type: | datetime |
Raises: |
ValueError – http_date doesn’t match any of the available time formats |
falcon.to_query_str(params, comma_delimited_lists=True, prefix=True)
[source]
Converts a dictionary of parameters to a query string.
Parameters: |
|
---|---|
Returns: |
A URI query string, including the ‘?’ prefix (unless |
Return type: |
falcon.get_http_status(status_code, default_reason='Unknown')
[source]
Gets both the http status code and description from just a code
Parameters: |
|
---|---|
Returns: |
status code e.g. “404 Not Found” |
Return type: | |
Raises: |
|
falcon.get_bound_method(obj, method_name)
[source]
Get a bound method of the given object by name.
Parameters: |
|
---|---|
Returns: |
Bound method, or |
Raises: |
|
class falcon.TimezoneGMT
[source]
GMT timezone class implementing the datetime.tzinfo
interface.
dst(dt)
[source]
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)
[source]
Get the name of this timezone.
Parameters: | dt (datetime.datetime) – Ignored |
---|---|
Returns: | “GMT” |
Return type: | str |
utcoffset(dt)
[source]
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 |
class falcon.Context
[source]
Convenience class to hold contextual information in its attributes.
This class is used as the default Request
and Response
context type (see Request.context_type
and Response.context_type
, respectively).
In Falcon versions prior to 2.0, the default context type was dict
. To ease the migration to attribute-based context object approach, this class also implements the mapping interface; that is, object attributes are linked to dictionary items, and vice versa. For instance:
>>> context = falcon.Context() >>> context.cache_strategy = 'lru' >>> context.get('cache_strategy') 'lru' >>> 'cache_strategy' in context True
Note
Python 2 specific dict
methods are exposed regardless of the Python language version, however, as they are delegated to the underlying __dict__
, a similar error would be raised as if attempting to use these methods for a usual Python 3 dict.
class falcon.ETag
[source]
Convenience class to represent a parsed HTTP entity-tag.
This class is simply a subclass of str
with a few helper methods and an extra attribute to indicate whether the entity-tag is weak or strong. The value of the string is equivalent to what RFC 7232 calls an “opaque-tag”, i.e. an entity-tag sans quotes and the weakness indicator.
Note
Given that a weak entity-tag comparison can be performed by using the ==
operator (per the example below), only a strong_compare()
method is provided.
Here is an example on_get()
method that demonstrates how to use instances of this class:
def on_get(self, req, resp): content_etag = self._get_content_etag() for etag in (req.if_none_match or []): if etag == '*' or etag == content_etag: resp.status = falcon.HTTP_304 return # ... resp.etag = content_etag resp.status = falcon.HTTP_200
(See also: RFC 7232)
is_weak
True
if the entity-tag is weak, otherwise False
.
Type: | bool |
---|
dumps()
[source]
Serialize the ETag to a string suitable for use in a precondition header.
(See also: RFC 7232, Section 2.3)
Returns: | An opaque quoted string, possibly prefixed by a weakness indicator W/ . |
---|---|
Return type: | str |
classmethod loads(etag_str)
[source]
Class method that deserializes a single entity-tag string from a precondition header.
Note
This method is meant to be used only for parsing a single entity-tag. It can not be used to parse a comma-separated list of values.
(See also: RFC 7232, Section 2.3)
Parameters: | etag_str (str) – An ASCII string representing a single entity-tag, as defined by RFC 7232. |
---|---|
Returns: | An instance of ~.ETag representing the parsed entity-tag. |
Return type: | ETag |
strong_compare(other)
[source]
Performs a strong entity-tag comparison.
Two entity-tags are equivalent if both are not weak and their opaque-tags match character-by-character.
(See also: RFC 7232, Section 2.3.2)
Parameters: | |
---|---|
Returns: |
|
Return type: |
© 2019 by Falcon contributors
Licensed under the Apache License, Version 2.0.
https://falcon.readthedocs.io/en/2.0.0/api/util.html