URI Functions

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')

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., 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

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., 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.


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.

  • query_string (str) – The query string to parse.
  • keep_blank (bool) – Set to True to return fields even if they do not have a value (default False). For comma-separated values, this option also determines whether or not empty elements in the parsed list are retained.
  • csv – Set to False in order to disable splitting query parameters on , (default True). Depending on the user agent, encoding lists as multiple occurrences of the same parameter might be preferable. In this case, setting parse_qs_csv to False will cause the framework to treat commas as literal characters in each occurring parameter value.

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:



TypeErrorquery_string was not a str.

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: TypeErrorquoted 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.

  • 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, or a list of such values. If a list, the value will be converted to a comma-delimited string of values (e.g., ‘thing=1,2,3’).
  • comma_delimited_lists (bool) – Set to False to encode list values by specifying multiple instances of the parameter (e.g., ‘thing=1&thing=2&thing=3’). Otherwise, parameters will be encoded as comma-separated values (e.g., ‘thing=1,2,3’). Defaults to True.
  • prefix (bool) – Set to False to exclude the ‘?’ prefix in the result string (default True).

A URI query string, including the ‘?’ prefix (unless prefix is False), or an empty string if no params are given (the dict is empty).

Return type:


falcon.get_http_status(status_code, default_reason='Unknown') [source]

Gets both the http status code and description from just a code

  • status_code – integer or string that can be converted to an integer
  • default_reason – default text to be appended to the status_code if the lookup does not find a result

status code e.g. “404 Not Found”

Return type:



ValueError – the value entered could not be converted to an integer

falcon.get_bound_method(obj, method_name) [source]

Get a bound method of the given object by name.

  • obj – Object on which to look up the method.
  • method_name – Name of the method to retrieve.

Bound method, or None if the method does not exist on the object.


AttributeError – The method exists, but it isn’t bound (most likely a class was passed, rather than an instance of that class).

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')
>>> 'cache_strategy' in context


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.


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

    # ...

    resp.etag = content_etag
    resp.status = falcon.HTTP_200

(See also: RFC 7232)


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.


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)

  • other (ETag) – The other ETag to which you are comparing
  • one. (this) –

True if the two entity-tags match, otherwise False.

Return type:


© 2019 by Falcon contributors
Licensed under the Apache License, Version 2.0.