doc(reference): Standardize docstring syntax

Unify the use of markup in docstrings, particulary relating to the use of
backticks and asterisks. Also clean up any remaining minor inconsistencies or
errors in the docstrings.

Closes #334
This commit is contained in:
Kurt Griffiths
2015-01-30 16:31:39 -06:00
parent 5886e6482a
commit da2bc234f8
21 changed files with 288 additions and 271 deletions

View File

@@ -14,6 +14,16 @@ $ tox -e py27,py33,pep8
* Docstrings are required for classes, attributes, methods, and functions. * Docstrings are required for classes, attributes, methods, and functions.
* Docstrings should utilize the [napolean style][docstrings] in order to make them read well, regardless of whether they are viewed through `help()` or on [Read the Docs][rtd]. * Docstrings should utilize the [napolean style][docstrings] in order to make them read well, regardless of whether they are viewed through `help()` or on [Read the Docs][rtd].
* Please try to be consistent with the way existing docstrings are formatted. In particular, note the use of single vs. double backticks as follows:
* Double backticks
* Inline code
* Variables
* Types
* Decorators
* Single backticks
* Methods
* Params
* Attributes
* Format non-trivial comments using your GitHub nick and one of these prefixes: * Format non-trivial comments using your GitHub nick and one of these prefixes:
* TODO(riker): Damage report! * TODO(riker): Damage report!
* NOTE(riker): Well, that's certainly good to know. * NOTE(riker): Well, that's certainly good to know.

View File

@@ -14,7 +14,6 @@ standard-compliant WSGI server.
.. autoclass:: falcon.API .. autoclass:: falcon.API
:members: :members:
:undoc-members:
.. autoclass:: falcon.RequestOptions .. autoclass:: falcon.RequestOptions
:members: :members:

View File

@@ -18,9 +18,9 @@ The middleware interface is defined as follows:
Args: Args:
req: Request object that will eventually be req: Request object that will eventually be
routed to an on_* responder method routed to an on_* responder method.
resp: Response object that will be routed to resp: Response object that will be routed to
the on_* responder the on_* responder.
""" """
def process_resource(self, req, resp, resource): def process_resource(self, req, resp, resource):
@@ -28,23 +28,23 @@ The middleware interface is defined as follows:
Args: Args:
req: Request object that will be passed to the req: Request object that will be passed to the
routed responder routed responder.
resp: Response object that will be passed to the resp: Response object that will be passed to the
responder responder.
resource: Resource object to which the request was resource: Resource object to which the request was
routed. May be None if no route was found for routed. May be None if no route was found for
the request the request.
""" """
def process_response(self, req, resp, resource) def process_response(self, req, resp, resource):
"""Post-processing of the response (after routing). """Post-processing of the response (after routing).
Args: Args:
req: Request object req: Request object.
resp: Response object resp: Response object.
resource: Resource object to which the request was resource: Resource object to which the request was
routed. May be None if no route was found routed. May be None if no route was found
for the request for the request.
""" """
Because middleware can execute before routing has occurred, if a Because middleware can execute before routing has occurred, if a

View File

@@ -3,14 +3,6 @@
Installation Installation
============ ============
Install from PyPI
-----------------
Falcon is super easy to install with pip. If you don't have pip yet,
please run—don't walk—to the
`pip website <http://www.pip-installer.org/en/latest/installing.html>`_
and get that happy little tool installed before you do anything else.
.. note:: .. note::
This documentation targets the upcoming 0.2 release of Falcon, This documentation targets the upcoming 0.2 release of Falcon,
@@ -18,6 +10,9 @@ and get that happy little tool installed before you do anything else.
``--pre`` flag with pip in order to install the Falcon 0.2 betas ``--pre`` flag with pip in order to install the Falcon 0.2 betas
and release candidates. and release candidates.
Install from PyPI
-----------------
If available, Falcon will compile itself with Cython for an extra If available, Falcon will compile itself with Cython for an extra
speed boost. The following will make sure Cython is installed first, and speed boost. The following will make sure Cython is installed first, and
that you always have the latest and greatest. that you always have the latest and greatest.
@@ -26,7 +21,8 @@ that you always have the latest and greatest.
$ pip install --upgrade cython falcon $ pip install --upgrade cython falcon
If you are on PyPy, you won't need Cython, of course: Note that if you are running on PyPy, you won't need Cython, so you can just
type:
.. code:: bash .. code:: bash

View File

@@ -36,7 +36,7 @@ class API(object):
Args: Args:
media_type (str, optional): Default media type to use as the value for media_type (str, optional): Default media type to use as the value for
the Content-Type header on responses. (default 'application/json') the Content-Type header on responses (default 'application/json').
middleware(object or list, optional): One or more objects middleware(object or list, optional): One or more objects
(instantiated classes) that implement the following middleware (instantiated classes) that implement the following middleware
component interface:: component interface::
@@ -47,9 +47,9 @@ class API(object):
Args: Args:
req: Request object that will eventually be req: Request object that will eventually be
routed to an on_* responder method routed to an on_* responder method.
resp: Response object that will be routed to resp: Response object that will be routed to
the on_* responder the on_* responder.
\""" \"""
def process_resource(self, req, resp, resource): def process_resource(self, req, resp, resource):
@@ -57,33 +57,36 @@ class API(object):
Args: Args:
req: Request object that will be passed to the req: Request object that will be passed to the
routed responder routed responder.
resp: Response object that will be passed to the resp: Response object that will be passed to the
responder responder.
resource: Resource object to which the request was resource: Resource object to which the request was
routed. May be None if no route was found for routed. May be None if no route was found for
the request the request.
\""" \"""
def process_response(self, req, resp, resource) def process_response(self, req, resp, resource)
\"""Post-processing of the response (after routing). \"""Post-processing of the response (after routing).
Args: Args:
req: Request object req: Request object.
resp: Response object resp: Response object.
resource: Resource object to which the request was resource: Resource object to which the request was
routed. May be None if no route was found routed. May be None if no route was found
for the request for the request.
\""" \"""
See also :ref:`Middleware <middleware>`. See also :ref:`Middleware <middleware>`.
request_type (Request, optional): Request-like class to use instead
request_type (Request, optional): ``Request``-like class to use instead
of Falcon's default class. Among other things, this feature of Falcon's default class. Among other things, this feature
affords inheriting from ``falcon.request.Request`` in order affords inheriting from ``falcon.request.Request`` in order
to override the ``context_type`` class variable. to override the ``context_type`` class variable.
(default falcon.request.Request) (default ``falcon.request.Request``)
response_type (Response, optional): Response-like class to use
response_type (Response, optional): ``Response``-like class to use
instead of Falcon's default class. (default instead of Falcon's default class. (default
falcon.response.Response) ``falcon.response.Response``)
Attributes: Attributes:
req_options (RequestOptions): A set of behavioral options related to req_options (RequestOptions): A set of behavioral options related to
@@ -265,7 +268,7 @@ class API(object):
Args: Args:
uri_template (str): A templatized URI. Care must be uri_template (str): A templatized URI. Care must be
taken to ensure the template does not mask any sink taken to ensure the template does not mask any sink
patterns, if any are registered (see also ``add_sink``). patterns, if any are registered (see also `add_sink`).
resource (instance): Object which represents a REST resource (instance): Object which represents a REST
resource. Falcon will pass "GET" requests to on_get, resource. Falcon will pass "GET" requests to on_get,
"PUT" requests to on_put, etc. If any HTTP methods are not "PUT" requests to on_put, etc. If any HTTP methods are not
@@ -311,7 +314,7 @@ class API(object):
Note: Note:
If the prefix overlaps a registered route template, If the prefix overlaps a registered route template,
the route will take precedence and mask the sink the route will take precedence and mask the sink
(see also ``add_route``). (see also `add_route`).
""" """
@@ -349,7 +352,7 @@ class API(object):
raise falcon.HTTPError(falcon.HTTP_792) raise falcon.HTTPError(falcon.HTTP_792)
Note: Note:
A handler can either raise an instance of HTTPError A handler can either raise an instance of ``HTTPError``
or modify resp manually in order to communicate or modify resp manually in order to communicate
information about the issue to the client. information about the issue to the client.
@@ -403,12 +406,12 @@ class API(object):
to override this behavior. to override this behavior.
Args: Args:
serializer (callable): A function of the form serializer (callable): A function taking the form
``func(req, exception)``, where `req` is the request ``func(req, exception)``, where `req` is the request
object that was passed to the responder method, and object that was passed to the responder method, and
`exception` is an instance of falcon.HTTPError. `exception` is an instance of ``falcon.HTTPError``.
The function must return a tuple of the form The function must return a ``tuple`` of the form
``(media_type, representation)``, or ``(None, None)`` (*media_type*, *representation*), or (``None``, ``None``)
if the client does not support any of the if the client does not support any of the
available media types. available media types.
@@ -428,7 +431,7 @@ class API(object):
Returns: Returns:
A 3-member tuple consisting of a responder callable, A 3-member tuple consisting of a responder callable,
a dict containing parsed path fields (if any were specified in a ``dict`` containing parsed path fields (if any were specified in
the matching route's URI template), and a reference to the the matching route's URI template), and a reference to the
responder's resource instance. responder's resource instance.
@@ -583,11 +586,11 @@ class API(object):
when resp.stream is a file-like object (default None). when resp.stream is a file-like object (default None).
Returns: Returns:
* If resp.body is not *None*, returns [resp.body], encoded * If resp.body is not ``None``, returns [resp.body], encoded
as UTF-8 if it is a Unicode string. Bytestrings are returned as UTF-8 if it is a Unicode string. Bytestrings are returned
as-is. as-is.
* If resp.data is not *None*, returns [resp.data] * If resp.data is not ``None``, returns [resp.data]
* If resp.stream is not *None*, returns resp.stream * If resp.stream is not ``None``, returns resp.stream
iterable using wsgi.file_wrapper, if possible. iterable using wsgi.file_wrapper, if possible.
* Otherwise, returns [] * Otherwise, returns []

View File

@@ -86,12 +86,12 @@ def default_serialize_error(req, exception):
override this one. override this one.
Args: Args:
req: Instance of falcon.Request req: Instance of ``falcon.Request``
exception: Instance of falcon.HTTPError exception: Instance of ``falcon.HTTPError``
Returns: Returns:
A tuple of the form ``(media_type, representation)``, or A ``tuple`` of the form (*media_type*, *representation*), or
``(None, None)`` if the client does not support any of the (``None``, ``None``) if the client does not support any of the
available media types. available media types.
""" """

View File

@@ -50,7 +50,7 @@ class HTTPUnauthorized(HTTPError):
description (str): Human-friendly description of the error, along with description (str): Human-friendly description of the error, along with
a helpful suggestion or two. a helpful suggestion or two.
scheme (str): Authentication scheme to use as the value of the scheme (str): Authentication scheme to use as the value of the
WWW-Authenticate header in the response (default *None*). WWW-Authenticate header in the response (default ``None``).
kwargs (optional): Same as for ``HTTPError``. kwargs (optional): Same as for ``HTTPError``.
""" """
@@ -111,7 +111,7 @@ class HTTPMethodNotAllowed(OptionalRepresentation, HTTPError):
Args: Args:
allowed_methods (list of str): Allowed HTTP methods for this allowed_methods (list of str): Allowed HTTP methods for this
resource (e.g., ['GET', 'POST', 'HEAD']). resource (e.g., ``['GET', 'POST', 'HEAD']``).
""" """
@@ -243,9 +243,9 @@ class HTTPRequestEntityTooLarge(HTTPError):
description (str): Human-friendly description of the error, along with description (str): Human-friendly description of the error, along with
a helpful suggestion or two. a helpful suggestion or two.
retry_after (datetime or int, optional): Value for the Retry-After retry_after (datetime or int, optional): Value for the Retry-After
header. If a datetime object, will serialize as an HTTP date. header. If a ``datetime`` object, will serialize as an HTTP date.
Otherwise, a non-negative int is expected, representing the number Otherwise, a non-negative ``int`` is expected, representing the
of seconds to wait. See also: http://goo.gl/DIrWr . number of seconds to wait. See also: http://goo.gl/DIrWr .
kwargs (optional): Same as for ``HTTPError``. kwargs (optional): Same as for ``HTTPError``.
""" """
@@ -337,9 +337,9 @@ class HTTPServiceUnavailable(HTTPError):
description (str): Human-friendly description of the error, along with description (str): Human-friendly description of the error, along with
a helpful suggestion or two. a helpful suggestion or two.
retry_after (datetime or int): Value for the Retry-After header. If a retry_after (datetime or int): Value for the Retry-After header. If a
datetime object, will serialize as an HTTP date. Otherwise, ``datetime`` object, will serialize as an HTTP date. Otherwise,
a non-negative int is expected, representing the number of seconds a non-negative ``int`` is expected, representing the number of
to wait. See also: http://goo.gl/DIrWr . seconds to wait. See also: http://goo.gl/DIrWr .
kwargs (optional): Same as for ``HTTPError``. kwargs (optional): Same as for ``HTTPError``.
""" """

View File

@@ -29,7 +29,7 @@ def before(action):
reference to the resource class instance associated with the reference to the resource class instance associated with the
request, and `params` is a dict of URI Template field names, request, and `params` is a dict of URI Template field names,
if any, that will be passed into the resource responder as if any, that will be passed into the resource responder as
*kwargs*. kwargs.
Note: Note:
Hooks may inject extra params as needed. For example:: Hooks may inject extra params as needed. For example::
@@ -161,8 +161,8 @@ def _has_self(spec):
Warning: Warning:
If a method's spec lists "self", that doesn't necessarily mean If a method's spec lists "self", that doesn't necessarily mean
that it should be called with a "self" param; if the method that it should be called with a `self` param; if the method
instance is bound, the caller must omit "self" on invocation. instance is bound, the caller must omit `self` on invocation.
""" """
@@ -174,13 +174,13 @@ def _wrap_with_after(action, responder, resource=None, is_method=False):
Args: Args:
action: A function with a signature similar to a resource responder action: A function with a signature similar to a resource responder
method, taking (req, resp, resource). method, taking the form ``func(req, resp, resource)``.
responder: The responder method to wrap. responder: The responder method to wrap.
resource: The resource affected by `action` (default None). If None, resource: The resource affected by `action` (default ``None``). If
`is_method` MUST BE True, so that the resource can be ``None``, `is_method` MUST BE True, so that the resource can be
derived from the `self` param that is passed into the wrapper derived from the `self` param that is passed into the wrapper.
is_method: Whether or not `responder` is an unbound method is_method: Whether or not `responder` is an unbound method
(default False) (default ``False``).
""" """
@@ -223,13 +223,13 @@ def _wrap_with_before(action, responder, resource=None, is_method=False):
Args: Args:
action: A function with a similar signature to a resource responder action: A function with a similar signature to a resource responder
method, taking (req, resp, resource, params) method, taking the form ``func(req, resp, resource, params)``.
responder: The responder method to wrap responder: The responder method to wrap
resource: The resource affected by `action` (default None). If None, resource: The resource affected by `action` (default ``None``). If
`is_method` MUST BE True, so that the resource can be ``None``, `is_method` MUST BE True, so that the resource can be
derived from the `self` param that is passed into the wrapper derived from the `self` param that is passed into the wrapper
is_method: Whether or not `responder` is an unbound method is_method: Whether or not `responder` is an unbound method
(default False) (default ``False``)
""" """

View File

@@ -54,11 +54,11 @@ class HTTPError(Exception):
title (str): Human-friendly error title (default ``None``). title (str): Human-friendly error title (default ``None``).
description (str): Human-friendly description of the error, along with description (str): Human-friendly description of the error, along with
a helpful suggestion or two (default ``None``). a helpful suggestion or two (default ``None``).
headers (dict or list): A dictionary of header names and values headers (dict or list): A ``dict`` of header names and values
to set, or list of (name, value) tuples. Both names and to set, or a ``list`` of (*name*, *value*) tuples. Both *name* and
values must be of type str or StringType, and only character *value* must be of type ``str`` or ``StringType``, and only
values 0x00 through 0xFF may be used on platforms that use character values 0x00 through 0xFF may be used on platforms that
wide characters. use wide characters.
Note: Note:
The Content-Type header, if present, will be overridden. If The Content-Type header, if present, will be overridden. If
@@ -68,8 +68,8 @@ class HTTPError(Exception):
client client
Note: Note:
Falcon can process a list of tuples slightly faster Falcon can process a list of ``tuple`` slightly faster
than a dict. than a ``dict``.
headers (dict): Extra headers to return in the headers (dict): Extra headers to return in the
response to the client (default ``None``). response to the client (default ``None``).
@@ -120,7 +120,7 @@ class HTTPError(Exception):
Args: Args:
obj_type: A dict-like type that will be used to store the obj_type: A dict-like type that will be used to store the
error information (default *dict*). error information (default ``dict``).
Returns: Returns:
A dictionary populated with the error's title, description, etc. A dictionary populated with the error's title, description, etc.

View File

@@ -59,35 +59,35 @@ class Request(object):
Attributes: Attributes:
protocol (str): Either 'http' or 'https'. protocol (str): Either 'http' or 'https'.
method (str): HTTP method requested (e.g., GET, POST, etc.) method (str): HTTP method requested (e.g., 'GET', 'POST', etc.)
host (str): Hostname requested by the client host (str): Hostname requested by the client
subdomain (str): Leftmost (i.e., most specific) subdomain from the subdomain (str): Leftmost (i.e., most specific) subdomain from the
hostname. If only a single domain name is given, `subdomain` hostname. If only a single domain name is given, `subdomain`
will be *None*. will be ``None``.
Note: Note:
If the hostname in the request is an IP address, the value If the hostname in the request is an IP address, the value
for `subdomain` is undefined. for `subdomain` is undefined.
user_agent (str): Value of the User-Agent header, or *None* if the user_agent (str): Value of the User-Agent header, or ``None`` if the
header is missing. header is missing.
app (str): Name of the WSGI app (if using WSGI's notion of virtual app (str): Name of the WSGI app (if using WSGI's notion of virtual
hosting). hosting).
env (dict): Reference to the WSGI *environ* dict passed in from the env (dict): Reference to the WSGI environ ``dict`` passed in from the
server. See also PEP-3333. server. See also PEP-3333.
context (dict): Dictionary to hold any data about the request which is context (dict): Dictionary to hold any data about the request which is
specific to your app (e.g. session object). Falcon itself will specific to your app (e.g. session object). Falcon itself will
not interact with this attribute after it has been initialized. not interact with this attribute after it has been initialized.
context_type (class): Class variable that determines the context_type (class): Class variable that determines the
factory or type to use for initializing the factory or type to use for initializing the
``context`` attribute. By default, the framework will `context` attribute. By default, the framework will
instantiate standard instantiate standard
``dict`` objects. However, You may override this behavior ``dict`` objects. However, You may override this behavior
by creating a custom child class of ``falcon.Request``, and by creating a custom child class of ``falcon.Request``, and
then passing that new class to ``falcon.API()`` by way of the then passing that new class to `falcon.API()` by way of the
latter's `request_type` parameter. latter's `request_type` parameter.
uri (str): The fully-qualified URI for the request. uri (str): The fully-qualified URI for the request.
url (str): alias for ``uri``. url (str): alias for `uri`.
relative_uri (str): The path + query string portion of the full URI. relative_uri (str): The path + query string portion of the full URI.
path (str): Path portion of the request URL (not including query path (str): Path portion of the request URL (not including query
string). string).
@@ -95,18 +95,19 @@ class Request(object):
the preceding '?' character. the preceding '?' character.
accept (str): Value of the Accept header, or '*/*' if the header is accept (str): Value of the Accept header, or '*/*' if the header is
missing. missing.
auth (str): Value of the Authorization header, or *None* if the header auth (str): Value of the Authorization header, or ``None`` if the
is missing. header is missing.
client_accepts_json (bool): True if the Accept header indicates that client_accepts_json (bool): ``True`` if the Accept header indicates
the client is willing to receive JSON, otherwise False. that the client is willing to receive JSON, otherwise ``False``.
client_accepts_msgpack (bool): True if the Accept header indicates client_accepts_msgpack (bool): ``True`` if the Accept header indicates
that the client is willing to receive MessagePack, otherwise False. that the client is willing to receive MessagePack, otherwise
client_accepts_xml (bool): True if the Accept header indicates that ``False``.
the client is willing to receive XML, otherwise False. client_accepts_xml (bool): ``True`` if the Accept header indicates that
content_type (str): Value of the Content-Type header, or *None* if the client is willing to receive XML, otherwise ``False``.
content_type (str): Value of the Content-Type header, or ``None`` if
the header is missing. the header is missing.
content_length (int): Value of the Content-Length header converted content_length (int): Value of the Content-Length header converted
to an int, or *None* if the header is missing. to an ``int``, or ``None`` if the header is missing.
stream: File-like object for reading the body of the request, if any. stream: File-like object for reading the body of the request, if any.
Note: Note:
@@ -118,18 +119,18 @@ class Request(object):
Note also that the character encoding for fields, before Note also that the character encoding for fields, before
percent-encoding non-ASCII bytes, is assumed to be percent-encoding non-ASCII bytes, is assumed to be
UTF-8. The special "_charset_" field is ignored if present. UTF-8. The special `_charset_` field is ignored if present.
Falcon expects form-encoded request bodies to be Falcon expects form-encoded request bodies to be
encoded according to the standard W3C algorithm (see encoded according to the standard W3C algorithm (see
also http://goo.gl/6rlcux). also http://goo.gl/6rlcux).
date (datetime): Value of the Date header, converted to a date (datetime): Value of the Date header, converted to a
`datetime.datetime` instance. The header value is assumed to ``datetime`` instance. The header value is assumed to
conform to RFC 1123. conform to RFC 1123.
expect (str): Value of the Expect header, or *None* if the expect (str): Value of the Expect header, or ``None`` if the
header is missing. header is missing.
range (tuple of int): A 2-member tuple parsed from the value of the range (tuple of int): A 2-member ``tuple`` parsed from the value of the
Range header. Range header.
The two members correspond to the first and last byte The two members correspond to the first and last byte
@@ -141,15 +142,15 @@ class Request(object):
Only continous ranges are supported (e.g., "bytes=0-0,-1" would Only continous ranges are supported (e.g., "bytes=0-0,-1" would
result in an HTTPBadRequest exception when the attribute is result in an HTTPBadRequest exception when the attribute is
accessed.) accessed.)
if_match (str): Value of the If-Match header, or *None* if the if_match (str): Value of the If-Match header, or ``None`` if the
header is missing. header is missing.
if_none_match (str): Value of the If-None-Match header, or *None* if_none_match (str): Value of the If-None-Match header, or ``None``
if the header is missing. if the header is missing.
if_modified_since (str): Value of the If-Modified-Since header, or if_modified_since (str): Value of the If-Modified-Since header, or
None if the header is missing. ``None`` if the header is missing.
if_unmodified_since (str): Value of the If-Unmodified-Sinc header, if_unmodified_since (str): Value of the If-Unmodified-Sinc header,
or *None* if the header is missing. or ``None`` if the header is missing.
if_range (str): Value of the If-Range header, or *None* if the if_range (str): Value of the If-Range header, or ``None`` if the
header is missing. header is missing.
headers (dict): Raw HTTP headers from the request with headers (dict): Raw HTTP headers from the request with
@@ -157,7 +158,7 @@ class Request(object):
to create this dict is done the first time this attribute to create this dict is done the first time this attribute
is accessed. This parsing can be costly, so unless you is accessed. This parsing can be costly, so unless you
need all the headers in this format, you should use the need all the headers in this format, you should use the
``get_header`` method or one of the convenience attributes `get_header` method or one of the convenience attributes
instead, to get a value for a specific header. instead, to get a value for a specific header.
params (dict): The mapping of request query parameter names to their params (dict): The mapping of request query parameter names to their
@@ -488,9 +489,9 @@ class Request(object):
media_type (str): An Internet media type to check. media_type (str): An Internet media type to check.
Returns: Returns:
bool: True if the client has indicated in the Accept header that bool: ``True`` if the client has indicated in the Accept header
it accepts the specified media type. Otherwise, returns that it accepts the specified media type. Otherwise, returns
False. ``False``.
""" """
accept = self.accept accept = self.accept
@@ -516,7 +517,7 @@ class Request(object):
Returns: Returns:
str: The client's preferred media type, based on the Accept str: The client's preferred media type, based on the Accept
header. Returns *None* if the client does not accept any header. Returns ``None`` if the client does not accept any
of the given types. of the given types.
""" """
@@ -534,12 +535,12 @@ class Request(object):
Args: Args:
name (str): Header name, case-insensitive (e.g., 'Content-Type') name (str): Header name, case-insensitive (e.g., 'Content-Type')
required (bool, optional): Set to True to raise HttpBadRequest required (bool, optional): Set to ``True`` to raise
instead of returning gracefully when the header is not found ``HTTPBadRequest`` instead of returning gracefully when the
(default False). header is not found (default ``False``).
Returns: Returns:
str: The value of the specified header if it exists, or *None* if str: The value of the specified header if it exists, or ``None`` if
the header is not found and is not required. the header is not found and is not required.
Raises: Raises:
@@ -589,20 +590,20 @@ class Request(object):
Note: Note:
Similar to the way multiple keys in form data is handled, Similar to the way multiple keys in form data is handled,
if a query parameter is assigned a comma-separated list of if a query parameter is assigned a comma-separated list of
values (e.g., foo=a,b,c), only one of those values will be values (e.g., 'foo=a,b,c'), only one of those values will be
returned, and it is undefined which one. Use returned, and it is undefined which one. Use
`req.get_param_as_list()` to retrieve all the values. `req.get_param_as_list()` to retrieve all the values.
Args: Args:
name (str): Parameter name, case-sensitive (e.g., 'sort') name (str): Parameter name, case-sensitive (e.g., 'sort').
required (bool, optional): Set to True to raise HTTPBadRequest required (bool, optional): Set to ``True`` to raise
instead of returning gracefully when the parameter is not ``HTTPBadRequest`` instead of returning ``None`` when the
found (default False) parameter is not found (default ``False``).
store (dict, optional): A dict-like object in which to place the store (dict, optional): A ``dict``-like object in which to place
value of the param, but only if the param is present. the value of the param, but only if the param is present.
Returns: Returns:
string: The value of the param as a string, or *None* if param is str: The value of the param as a string, or ``None`` if param is
not found and is not required. not found and is not required.
Raises: Raises:
@@ -637,24 +638,25 @@ class Request(object):
"""Return the value of a query string parameter as an int. """Return the value of a query string parameter as an int.
Args: Args:
name (str): Parameter name, case-sensitive (e.g., 'limit') name (str): Parameter name, case-sensitive (e.g., 'limit').
required (bool, optional): Set to True to raise HTTPBadRequest required (bool, optional): Set to ``True`` to raise
instead of returning gracefully when the parameter is not ``HTTPBadRequest`` instead of returning ``None`` when the
found or is not an integer (default False). parameter is not found or is not an integer (default
``False``).
min (int, optional): Set to the minimum value allowed for this min (int, optional): Set to the minimum value allowed for this
param. If the param is found and it is less than min, an param. If the param is found and it is less than min, an
HTTPError is raised. ``HTTPError`` is raised.
max (int, optional): Set to the maximum value allowed for this max (int, optional): Set to the maximum value allowed for this
param. If the param is found and its value is greater than param. If the param is found and its value is greater than
max, an HTTPError is raised. max, an ``HTTPError`` is raised.
store (dict, optional): A dict-like object in which to place the store (dict, optional): A ``dict``-like object in which to place
value of the param, but only if the param is found (default the value of the param, but only if the param is found
*None*). (default ``None``).
Returns: Returns:
int: The value of the param if it is found and can be converted to int: The value of the param if it is found and can be converted to
an integer. If the param is not found, returns *None*, unless an integer. If the param is not found, returns ``None``, unless
``required`` is True. `required` is ``True``.
Raises Raises
HTTPBadRequest: The param was not found in the request, even though HTTPBadRequest: The param was not found in the request, even though
@@ -701,27 +703,31 @@ class Request(object):
blank_as_true=False): blank_as_true=False):
"""Return the value of a query string parameter as a boolean """Return the value of a query string parameter as a boolean
The following bool-like strings are supported:: The following boolean strings are supported::
TRUE_STRINGS = ('true', 'True', 'yes') TRUE_STRINGS = ('true', 'True', 'yes')
FALSE_STRINGS = ('false', 'False', 'no') FALSE_STRINGS = ('false', 'False', 'no')
Args: Args:
name (str): Parameter name, case-sensitive (e.g., 'limit') name (str): Parameter name, case-sensitive (e.g., 'detailed').
required (bool, optional): Set to True to raise HTTPBadRequest required (bool, optional): Set to ``True`` to raise
instead of returning gracefully when the parameter is not ``HTTPBadRequest`` instead of returning ``None`` when the
found or is not a recognized bool-ish string (default False). parameter is not found or is not a recognized boolean
store (dict, optional): A dict-like object in which to place the string (default ``False``).
value of the param, but only if the param is found (default store (dict, optional): A ``dict``-like object in which to place
*None*). the value of the param, but only if the param is found (default
blank_as_true (bool): If True, empty strings will be treated as ``None``).
True. keep_blank_qs_values must be set on the Request (or API blank_as_true (bool): If ``True``, an empty string value will be
object and inherited) for empty strings to not be filtered. treated as ``True``. Normally empty strings are ignored, so
if you would like to recognize them, you must set the
`keep_blank_qs_values` request option to ``True``. Request
options are set globally for each instance of
``falcon.API`` through that instance's `req_options` attribute.
Returns: Returns:
bool: The value of the param if it is found and can be converted bool: The value of the param if it is found and can be converted
to a boolean. If the param is not found, returns *None* unless to a ``bool``. If the param is not found, returns ``None``
required is True. unless required is ``True``.
Raises: Raises:
HTTPBadRequest: A required param is missing from the request. HTTPBadRequest: A required param is missing from the request.
@@ -766,22 +772,22 @@ class Request(object):
ala *application/x-www-form-urlencoded*. ala *application/x-www-form-urlencoded*.
Args: Args:
name (str): Parameter name, case-sensitive (e.g., 'limit') name (str): Parameter name, case-sensitive (e.g., 'ids').
transform (callable, optional): An optional transform function transform (callable, optional): An optional transform function
that takes as input each element in the list as a string and that takes as input each element in the list as a ``str`` and
outputs a transformed element for inclusion in the list that outputs a transformed element for inclusion in the list that
will be returned. For example, passing the int function will will be returned. For example, passing ``int`` will
transform list items into numbers. transform list items into numbers.
required (bool, optional): Set to True to raise HTTPBadRequest required (bool, optional): Set to ``True`` to raise
instead of returning gracefully when the parameter is not ``HTTPBadRequest`` instead of returning ``None`` when the
found or is not an integer (default False) parameter is not found (default ``False``).
store (dict, optional): A dict-like object in which to place the store (dict, optional): A ``dict``-like object in which to place
value of the param, but only if the param is found (default the value of the param, but only if the param is found (default
*None*). ``None``).
Returns: Returns:
list: The value of the param if it is found. Otherwise, returns list: The value of the param if it is found. Otherwise, returns
*None* unless required is True. Empty list elements will be ``None`` unless required is True. Empty list elements will be
discarded. For example a query string containing this:: discarded. For example a query string containing this::
things=1,,3 things=1,,3
@@ -796,6 +802,8 @@ class Request(object):
Raises: Raises:
HTTPBadRequest: A required param is missing from the request. HTTPBadRequest: A required param is missing from the request.
HTTPInvalidParam: A tranform function raised an instance of
``ValueError``.
""" """
@@ -841,9 +849,8 @@ class Request(object):
result out to the WSGI server's error stream (`wsgi.error`). result out to the WSGI server's error stream (`wsgi.error`).
Args: Args:
message (str): A string describing the problem. If a byte-string, message (str or unicode): Description of the problem. On Python 2,
it is simply written out as-is. Unicode strings will be instances of ``unicode`` will be converted to UTF-8.
converted to UTF-8.
""" """
@@ -917,11 +924,11 @@ class Request(object):
# PERF: To avoid typos and improve storage space and speed over a dict. # PERF: To avoid typos and improve storage space and speed over a dict.
class RequestOptions(object): class RequestOptions(object):
"""This class is a container for Request options. """This class is a container for ``Request`` options.
Attributes: Attributes:
keep_blank_qs_values (bool): Set to ``True`` in order to retain keep_blank_qs_values (bool): Set to ``True`` in order to retain
blank values in query string parameters (default ``False``.) blank values in query string parameters (default ``False``).
""" """
__slots__ = ( __slots__ = (

View File

@@ -18,7 +18,7 @@ def header_property(wsgi_name):
Args: Args:
wsgi_name (str): Case-sensitive name of the header as it would wsgi_name (str): Case-sensitive name of the header as it would
appear in the WSGI environ dict (i.e., 'HTTP_*') appear in the WSGI environ ``dict`` (i.e., 'HTTP_*')
Returns: Returns:
A property instance than can be assigned to a class variable. A property instance than can be assigned to a class variable.
@@ -35,20 +35,21 @@ def header_property(wsgi_name):
class Body(object): class Body(object):
"""Wrap wsgi.input streams to make them more robust. """Wrap *wsgi.input* streams to make them more robust.
The socket._fileobject and io.BufferedReader are sometimes used ``socket._fileobject`` and ``io.BufferedReader`` are sometimes used
to implement wsgi.input. However, app developers are often burned to implement *wsgi.input*. However, app developers are often burned
by the fact that the read() method for these objects block by the fact that the `read()` method for these objects block
indefinitely if either no size is passed, or a size greater than indefinitely if either no size is passed, or a size greater than
the request's content length is passed to the method. the request's content length is passed to the method.
This class normalizes wsgi.input behavior between WSGI servers This class normalizes *wsgi.input* behavior between WSGI servers
by implementing non-blocking behavior for the cases mentioned by implementing non-blocking behavior for the cases mentioned
above. above.
Args: Args:
stream: Instance of socket._fileobject from environ['wsgi.input'] stream: Instance of ``socket._fileobject`` from
``environ['wsgi.input']``
stream_len: Expected content length of the stream. stream_len: Expected content length of the stream.
""" """

View File

@@ -50,28 +50,28 @@ class Response(object):
simply ``bytes`` in Python 3). See also the note below. simply ``bytes`` in Python 3). See also the note below.
Note: Note:
Under Python 2.x, if your content is of type *str*, using Under Python 2.x, if your content is of type ``str``, using
the `data` attribute instead of `body` is the most the `data` attribute instead of `body` is the most
efficient approach. However, if efficient approach. However, if
your text is of type *unicode*, you will need to use the your text is of type ``unicode``, you will need to use the
*body* attribute instead. `body` attribute instead.
Under Python 3.x, on the other hand, the 2.x *str* type can Under Python 3.x, on the other hand, the 2.x ``str`` type can
be thought of as be thought of as
having been replaced by what was once the *unicode* type, having been replaced by what was once the ``unicode`` type,
and so you will need to always use the `body` attribute for and so you will need to always use the `body` attribute for
strings to strings to
ensure Unicode characters are properly encoded in the ensure Unicode characters are properly encoded in the
HTTP response. HTTP response.
stream: Either a file-like object with a *read()* method that takes stream: Either a file-like object with a `read()` method that takes
an optional size argument and returns a block of bytes, or an an optional size argument and returns a block of bytes, or an
iterable object, representing response content, and yielding iterable object, representing response content, and yielding
blocks as byte strings. Falcon will use wsgi.file_wrapper, if blocks as byte strings. Falcon will use *wsgi.file_wrapper*, if
provided by the WSGI server, in order to efficiently serve provided by the WSGI server, in order to efficiently serve
file-like objects. file-like objects.
stream_len (int): Expected length of *stream* (e.g., file size). stream_len (int): Expected length of `stream` (e.g., file size).
""" """
__slots__ = ( __slots__ = (
@@ -125,10 +125,10 @@ class Response(object):
return self._body_encoded return self._body_encoded
def set_stream(self, stream, stream_len): def set_stream(self, stream, stream_len):
"""Convenience method for setting both stream and stream_len. """Convenience method for setting both `stream` and `stream_len`.
Although the stream and stream_len properties may be set Although the `stream` and `stream_len` properties may be set
directly, using this method ensures stream_len is not directly, using this method ensures `stream_len` is not
accidentally neglected. accidentally neglected.
""" """
@@ -144,11 +144,11 @@ class Response(object):
Args: Args:
name (str): Header name to set (case-insensitive). Must be of name (str): Header name to set (case-insensitive). Must be of
type str or StringType, and only character values 0x00 type ``str`` or ``StringType``, and only character values 0x00
through 0xFF may be used on platforms that use wide through 0xFF may be used on platforms that use wide
characters. characters.
value (str): Value for the header. Must be of type str or value (str): Value for the header. Must be of type ``str`` or
StringType, and only character values 0x00 through 0xFF ``StringType``, and only character values 0x00 through 0xFF
may be used on platforms that use wide characters. may be used on platforms that use wide characters.
""" """
@@ -166,11 +166,11 @@ class Response(object):
Args: Args:
name (str): Header name to set (case-insensitive). Must be of name (str): Header name to set (case-insensitive). Must be of
type str or StringType, and only character values 0x00 type ``str`` or ``StringType``, and only character values 0x00
through 0xFF may be used on platforms that use wide through 0xFF may be used on platforms that use wide
characters. characters.
value (str): Value for the header. Must be of type str or value (str): Value for the header. Must be of type ``str`` or
StringType, and only character values 0x00 through 0xFF ``StringType``, and only character values 0x00 through 0xFF
may be used on platforms that use wide characters. may be used on platforms that use wide characters.
""" """
@@ -188,17 +188,17 @@ class Response(object):
Args: Args:
headers (dict or list): A dictionary of header names and values headers (dict or list): A dictionary of header names and values
to set, or list of (name, value) tuples. Both names and to set, or ``list`` of (*name*, *value*) tuples. Both *name*
values must be of type str or StringType, and only character and *value* must be of type ``str`` or ``StringType``, and
values 0x00 through 0xFF may be used on platforms that use only character values 0x00 through 0xFF may be used on
wide characters. platforms that use wide characters.
Note: Note:
Falcon can process a list of tuples slightly faster Falcon can process a list of tuples slightly faster
than a dict. than a dict.
Raises: Raises:
ValueError: headers was not a dictionary or list of tuples. ValueError: `headers` was not a ``dict`` or ``list`` of ``tuple``.
""" """
@@ -236,12 +236,12 @@ class Response(object):
Kwargs: Kwargs:
title (str): Human-readable label for the destination of title (str): Human-readable label for the destination of
the link (default None). If the title includes non-ASCII the link (default ``None``). If the title includes non-ASCII
characters, you will need to use `title_star` instead, or characters, you will need to use `title_star` instead, or
provide both a US-ASCII version using `title` and a provide both a US-ASCII version using `title` and a
Unicode version using `title_star`. Unicode version using `title_star`.
title_star (tuple of str): Localized title describing the title_star (tuple of str): Localized title describing the
destination of the link (default None). The value must be a destination of the link (default ``None``). The value must be a
two-member tuple in the form of (*language-tag*, *text*), two-member tuple in the form of (*language-tag*, *text*),
where *language-tag* is a standard language identifier as where *language-tag* is a standard language identifier as
defined in RFC 5646, Section 2.1, and *text* is a Unicode defined in RFC 5646, Section 2.1, and *text* is a Unicode
@@ -255,7 +255,7 @@ class Response(object):
Note: Note:
*text* will always be encoded as UTF-8. If the string *text* will always be encoded as UTF-8. If the string
contains non-ASCII characters, it should be passed as contains non-ASCII characters, it should be passed as
a "unicode" type string (requires the 'u' prefix in a ``unicode`` type string (requires the 'u' prefix in
Python 2). Python 2).
anchor (str): Override the context IRI with a different URI anchor (str): Override the context IRI with a different URI
@@ -263,13 +263,13 @@ class Response(object):
simply the IRI of the requested resource. The value simply the IRI of the requested resource. The value
provided may be a relative URI. provided may be a relative URI.
hreflang (str or iterable): Either a single *language-tag*, or hreflang (str or iterable): Either a single *language-tag*, or
a list or tuple of such tags to provide a hint to the client a ``list`` or ``tuple`` of such tags to provide a hint to the
as to the language of the result of following the link. A client as to the language of the result of following the link.
list of tags may be given in order to indicate to the A list of tags may be given in order to indicate to the
client that the target resource is available in multiple client that the target resource is available in multiple
languages. languages.
type_hint(str): Provides a hint as to the media type of the type_hint(str): Provides a hint as to the media type of the
result of dereferencing the link (default None). As noted result of dereferencing the link (default ``None``). As noted
in RFC 5988, this is only a hint and does not override the in RFC 5988, this is only a hint and does not override the
Content-Type header returned when the link is followed. Content-Type header returned when the link is followed.
@@ -344,15 +344,15 @@ class Response(object):
'Content-Range', 'Content-Range',
"""A tuple to use in constructing a value for the Content-Range header. """A tuple to use in constructing a value for the Content-Range header.
The tuple has the form ``(start, end, length)``, where *start* and The tuple has the form (*start*, *end*, *length*), where *start* and
*end* designate the byte range (inclusive), and *length* is the *end* designate the byte range (inclusive), and *length* is the
total number of bytes, or '*' if unknown. You may use *int*'s for total number of bytes, or '*' if unknown. You may pass ``int``'s for
these numbers (no need to convert to a *str* first). these numbers (no need to convert to ``str`` beforehand).
Note: Note:
You only need to use the alternate form, "bytes */1234", for You only need to use the alternate form, 'bytes */1234', for
responses that use the status "416 Range Not Satisfiable". In this responses that use the status '416 Range Not Satisfiable'. In this
case, raising falcon.HTTPRangeNotSatisfiable will do the right case, raising ``falcon.HTTPRangeNotSatisfiable`` will do the right
thing. thing.
See also: http://goo.gl/Iglhp See also: http://goo.gl/Iglhp
@@ -369,10 +369,10 @@ class Response(object):
last_modified = header_property( last_modified = header_property(
'Last-Modified', 'Last-Modified',
"""Sets the Last-Modified header. Set to a datetime (UTC) instance. """Sets the Last-Modified header. Set to a ``datetime`` (UTC) instance.
Note: Note:
Falcon will format the datetime as an HTTP date. Falcon will format the ``datetime`` as an HTTP date string.
""", """,
dt_to_http) dt_to_http)
@@ -395,8 +395,8 @@ class Response(object):
"""Value to use for the Vary header. """Value to use for the Vary header.
Set this property to an iterable of header names. For a single Set this property to an iterable of header names. For a single
asterisk or field value, simply pass a single-element list or asterisk or field value, simply pass a single-element ``list`` or
tuple. ``tuple``.
"Tells downstream proxies how to match future request headers "Tells downstream proxies how to match future request headers
to decide whether the cached response can be used rather than to decide whether the cached response can be used rather than
@@ -414,7 +414,7 @@ class Response(object):
Args: Args:
media_type: Default media type to use for the Content-Type media_type: Default media type to use for the Content-Type
header if the header was not set explicitly (default None). header if the header was not set explicitly (default ``None``).
""" """

View File

@@ -22,7 +22,7 @@ def header_property(name, doc, transform=None):
transform: Transformation function to use when setting the transform: Transformation function to use when setting the
property. The value will be passed to the function, and property. The value will be passed to the function, and
the function should return the transformed value to use the function should return the transformed value to use
as the value of the header (default None) as the value of the header (default ``None``).
""" """
normalized_name = name.lower() normalized_name = name.lower()
@@ -50,7 +50,7 @@ def format_range(value):
"""Formats a range header tuple per the HTTP spec. """Formats a range header tuple per the HTTP spec.
Args: Args:
value: Tuple passed to req.range value: ``tuple`` passed to `req.range`
""" """

View File

@@ -67,7 +67,7 @@ def compile_uri_template(template):
# NOTE(kgriffs): Published method; take care to avoid breaking changes. # NOTE(kgriffs): Published method; take care to avoid breaking changes.
def create_http_method_map(resource, uri_fields, before, after): def create_http_method_map(resource, uri_fields, before, after):
"""Maps HTTP methods (e.g., GET, POST) to methods of a resource object. """Maps HTTP methods (e.g., 'GET', 'POST') to methods of a resource object.
Args: Args:
resource: An object with *responder* methods, following the naming resource: An object with *responder* methods, following the naming
@@ -78,9 +78,9 @@ def create_http_method_map(resource, uri_fields, before, after):
uri_fields: A set of field names from the route's URI template uri_fields: A set of field names from the route's URI template
that a responder must support in order to avoid "method not that a responder must support in order to avoid "method not
allowed". allowed".
before: An action hook or list of hooks to be called before each before: An action hook or ``list`` of hooks to be called before each
*on_\** responder defined by the resource. *on_\** responder defined by the resource.
after: An action hook or list of hooks to be called after each after: An action hook or ``list`` of hooks to be called after each
*on_\** responder defined by the resource. *on_\** responder defined by the resource.
Returns: Returns:

View File

@@ -26,20 +26,20 @@ from falcon.testing.helpers import create_environ
class TestBase(unittest.TestCase): class TestBase(unittest.TestCase):
"""Extends *testtools.TestCase* to support WSGI integration testing. """Extends ``testtools.TestCase`` to support WSGI integration testing.
`TestBase` provides a base class that provides some extra plumbing to ``TestBase`` provides a base class that provides some extra plumbing to
help simulate WSGI calls without having to actually host your API help simulate WSGI calls without having to actually host your API
in a server. in a server.
Note: Note:
If *testtools* is not available, *unittest* is used instead. If ``testtools`` is not available, ``unittest`` is used instead.
Attributes: Attributes:
api (falcon.API): An API instance to target when simulating api (falcon.API): An API instance to target when simulating
requests. Defaults to ``falcon.API()``. requests. Defaults to ``falcon.API()``.
srmock (falcon.testing.StartResponseMock): Provides a callable srmock (falcon.testing.StartResponseMock): Provides a callable
that simulates the behavior of the *start_response* argument that simulates the behavior of the `start_response` argument
that the server would normally pass into the WSGI app. The that the server would normally pass into the WSGI app. The
mock object captures various information from the app's mock object captures various information from the app's
response to the simulated request. response to the simulated request.
@@ -84,7 +84,7 @@ class TestBase(unittest.TestCase):
Args: Args:
path (str): The path to request. path (str): The path to request.
decode (str, optional): If this is set to a character encoding, decode (str, optional): If this is set to a character encoding,
such as "utf-8", `simulate_request` will assume the such as 'utf-8', `simulate_request` will assume the
response is a single byte string, and will decode it as the response is a single byte string, and will decode it as the
result of the request, rather than simply returning the result of the request, rather than simply returning the
standard WSGI iterable. standard WSGI iterable.

View File

@@ -57,32 +57,33 @@ def create_environ(path='/', query_string='', protocol='HTTP/1.1',
headers=None, app='', body='', method='GET', headers=None, app='', body='', method='GET',
wsgierrors=None, file_wrapper=None): wsgierrors=None, file_wrapper=None):
"""Creates a mock PEP-3333 environ dict for simulating WSGI requests. """Creates a mock PEP-3333 environ ``dict`` for simulating WSGI requests.
Args: Args:
path (str, optional): The path for the request (default '/') path (str, optional): The path for the request (default '/')
query_string (str, optional): The query string to simulate, without a query_string (str, optional): The query string to simulate, without a
leading '?' (default '') leading '?' (default '')
protocol (str, optional): The HTTP protocol to simulate protocol (str, optional): The HTTP protocol to simulate
(default 'HTTP/1.1'). If set 'HTTP/1.0', the Host header (default 'HTTP/1.1'). If set to 'HTTP/1.0', the Host header
will not be added to the environment. will not be added to the environment.
scheme (str): URL scheme, either 'http' or 'https' (default 'http') scheme (str): URL scheme, either 'http' or 'https' (default 'http')
host(str): Hostname for the request (default 'falconframework.org') host(str): Hostname for the request (default 'falconframework.org')
port (str or int, optional): The TCP port to simulate. Defaults to 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' the standard port used by the given scheme (i.e., 80 for 'http'
and 443 for 'https'). and 443 for 'https').
headers (dict or list, optional): Headers as a dict or an headers (dict or list, optional): Headers as a ``dict`` or an
iterable collection of ``(key, value)`` tuples iterable collection of (*key*, *value*) ``tuple``'s
app (str): Value for the SCRIPT_NAME environ variable, described in app (str): Value for the ``SCRIPT_NAME`` environ variable, described in
PEP-333: 'The initial portion of the request URL's "path" that PEP-333: 'The initial portion of the request URL's "path" that
corresponds to the application object, so that the application corresponds to the application object, so that the application
knows its virtual "location". This may be an empty string, if the knows its virtual "location". This may be an empty string, if the
application corresponds to the "root" of the server.' (default '') application corresponds to the "root" of the server.' (default '')
body (str or unicode): The body of the request (default '') body (str or unicode): The body of the request (default '')
method (str): The HTTP method to use (default 'GET') method (str): The HTTP method to use (default 'GET')
wsgierrors (io): The stream to use as wsgierrors (default sys.stderr) wsgierrors (io): The stream to use as *wsgierrors*
(default ``sys.stderr``)
file_wrapper: Callable that returns an iterable, to be used as file_wrapper: Callable that returns an iterable, to be used as
the value for 'wsgi.file_wrapper' in the environ. the value for *wsgi.file_wrapper* in the environ.
""" """

View File

@@ -19,7 +19,7 @@ from .helpers import rand_string
class TestResource: class TestResource:
"""Mock resource for integration testing. """Mock resource for integration testing.
This class implements the *on_get* responder, captures This class implements the `on_get` responder, captures
request data, and sets response body and headers. request data, and sets response body and headers.
Child classes may add additional methods and attributes as Child classes may add additional methods and attributes as
@@ -30,13 +30,14 @@ class TestResource:
sample_body (str): Random body string 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 resp_headers (dict): Sample headers to use in the response
req (falcon.Request): Request object passed into the *on_get* req (falcon.Request): Request object passed into the `on_get`
responder responder.
resp (falcon.Response): Response object passed into the *on_get* resp (falcon.Response): Response object passed into the `on_get`
responder responder.
kwargs (dict): Keyword arguments passed into the *on_get* kwargs (dict): Keyword arguments passed into the `on_get`
responder, if any responder, if any.
called (bool): True if *on_get* was ever called; False otherwise called (bool): ``True`` if `on_get` was ever called; ``False``
otherwise.
""" """
@@ -57,13 +58,13 @@ class TestResource:
def on_get(self, req, resp, **kwargs): def on_get(self, req, resp, **kwargs):
"""GET responder. """GET responder.
Captures req, resp, and kwargs. Also sets up a sample response. Captures `req`, `resp`, and `kwargs`. Also sets up a sample response.
Args: Args:
req: Falcon `Request` instance req: Falcon ``Request`` instance.
resp: Falcon `Response` instance resp: Falcon ``Response`` instance.
kwargs: URI template *name=value* pairs, if any, along with kwargs: URI template *name=value* pairs, if any, along with
any extra args injected by middleware any extra args injected by middleware.
""" """

View File

@@ -16,16 +16,16 @@ from falcon import util
class StartResponseMock: class StartResponseMock:
"""Mock object that represents a WSGI "start_response" callable. """Mock object representing a WSGI `start_response` callable.
Attributes: Attributes:
call_count (int): Number of times start_response was called. call_count (int): Number of times `start_response` was called.
status (str): HTTP status line, e.g. "785 TPS Cover Sheet status (str): HTTP status line, e.g. '785 TPS Cover Sheet
not attached". not attached'.
headers (list): Raw headers list passed to `start_response`, headers (list): Raw headers list passed to `start_response`,
per PEP-333. per PEP-333.
headers_dict (dict): Headers as a case-insensitive headers_dict (dict): Headers as a case-insensitive
dictionary, instead of a list. ``dict``-like object, instead of a ``list``.
""" """

View File

@@ -45,7 +45,7 @@ def deprecated(instructions):
Args: Args:
instructions (str): Specific guidance for the developer, e.g.: instructions (str): Specific guidance for the developer, e.g.:
"Please migrate to add_proxy(...)" 'Please migrate to add_proxy(...)''
""" """
def decorator(func): def decorator(func):
@@ -70,14 +70,13 @@ def deprecated(instructions):
def dt_to_http(dt): def dt_to_http(dt):
"""Converts a datetime instance to an HTTP date string. """Converts a ``datetime`` instance to an HTTP date string.
Args: Args:
dt (datetime): A *datetime.datetime* instance, assumed to be UTC. dt (datetime): A ``datetime`` instance to convert, assumed to be UTC.
Returns: Returns:
str: An RFC 1123 date string, e.g.: str: An RFC 1123 date string, e.g.: "Tue, 15 Nov 1994 12:45:26 GMT".
"Tue, 15 Nov 1994 12:45:26 GMT".
""" """
@@ -102,18 +101,18 @@ def http_date_to_dt(http_date):
def to_query_str(params): def to_query_str(params):
"""Converts a dict of params to a query string. """Converts a dictionary of params to a query string.
Args: Args:
params (dict): A dictionary of parameters, where each key is a params (dict): A dictionary of parameters, where each key is a
parameter name, and each value is either a string or parameter name, and each value is either a ``str`` or
something that can be converted into a string. If `params` something that can be converted into a ``str``. If `params`
is a list, it will be converted to a comma-delimited string is a ``list``, it will be converted to a comma-delimited string
of values (e.g., "thing=1,2,3") of values (e.g., 'thing=1,2,3')
Returns: Returns:
str: A URI query string including the "?" prefix, or an empty string str: A URI query string including the '?' prefix, or an empty string
if no params are given (the dict is empty). if no params are given (the ``dict`` is empty).
""" """
if not params: if not params:
@@ -145,7 +144,7 @@ def get_bound_method(obj, method_name):
method_name: Name of the method to retrieve. method_name: Name of the method to retrieve.
Returns: Returns:
Bound method, or `None` if the method does not exist on Bound method, or ``None`` if the method does not exist on
the object. the object.
Raises: Raises:

View File

@@ -24,8 +24,8 @@ class CaseInsensitiveDict(collections.MutableMapping): # pragma: no cover
A case-insensitive ``dict``-like object. A case-insensitive ``dict``-like object.
Implements all methods and operations of Implements all methods and operations of
``collections.MutableMapping`` as well as dict's ``copy``. Also ``collections.MutableMapping`` as well as dict's `copy`. Also
provides ``lower_items``. provides `lower_items`.
All keys are expected to be strings. The structure remembers the All keys are expected to be strings. The structure remembers the
case of the last key to be set, and ``iter(instance)``, case of the last key to be set, and ``iter(instance)``,

View File

@@ -82,12 +82,12 @@ all other "disallowed" characters by percent-encoding them.
Note: Note:
This utility is faster in the average case than the similar This utility is faster in the average case than the similar
`quote` function found in urlib. It also strives to be easier `quote` function found in ``urlib``. It also strives to be easier
to use by assuming a sensible default of allowed characters. to use by assuming a sensible default of allowed characters.
Args: Args:
uri (str): URI or part of a URI to encode. If this is a wide 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 string (i.e., ``six.text_type``), it will be encoded to
a UTF-8 byte array and any multibyte sequences will a UTF-8 byte array and any multibyte sequences will
be percent-encoded as-is. be percent-encoded as-is.
@@ -119,7 +119,7 @@ Args:
uri (str): URI fragment to encode. It is assumed not to cross delimiter uri (str): URI fragment to encode. It is assumed not to cross delimiter
boundaries, and so any reserved URI delimiter characters boundaries, and so any reserved URI delimiter characters
included in it will be escaped. If `value` is a wide included in it will be escaped. If `value` is a wide
string (i.e., *six.text_type*), it will be encoded to string (i.e., ``six.text_type``), it will be encoded to
a UTF-8 byte array and any multibyte sequences will a UTF-8 byte array and any multibyte sequences will
be percent-encoded as-is. be percent-encoded as-is.
@@ -140,7 +140,7 @@ if six.PY2: # pragma: no cover
def decode(encoded_uri): def decode(encoded_uri):
"""Decodes percent-encoded characters in a URI or query string. """Decodes percent-encoded characters in a URI or query string.
This function models the behavior of urllib.parse.unquote_plus, but This function models the behavior of `urllib.parse.unquote_plus`, but
is faster. It is also more robust, in that it will decode escaped is faster. It is also more robust, in that it will decode escaped
UTF-8 mutibyte sequences. UTF-8 mutibyte sequences.
@@ -148,7 +148,7 @@ if six.PY2: # pragma: no cover
encoded_uri (str): An encoded URI (full or partial). encoded_uri (str): An encoded URI (full or partial).
Returns: Returns:
str: A decoded URL. Will be of type *unicode* on Python 2 IFF the str: A decoded URL. Will be of type ``unicode`` on Python 2 IFF the
URL contained escaped non-ASCII characters, in which case URL contained escaped non-ASCII characters, in which case
UTF-8 is assumed per RFC 3986. UTF-8 is assumed per RFC 3986.
@@ -249,31 +249,31 @@ def parse_query_string(query_string, keep_blank_qs_values=False):
"""Parse a query string into a dict. """Parse a query string into a dict.
Query string parameters are assumed to use standard form-encoding. Only Query string parameters are assumed to use standard form-encoding. Only
parameters with values are parsed. for example, given "foo=bar&flag", parameters with values are parsed. for example, given 'foo=bar&flag',
this function would ignore "flag" unless the keep_blank_qs_values option this function would ignore 'flag' unless the `keep_blank_qs_values` option
is set. is set.
Note: Note:
In addition to the standard HTML form-based method for specifying In addition to the standard HTML form-based method for specifying
lists by repeating a given param multiple times, Falcon supports lists by repeating a given param multiple times, Falcon supports
a more compact form in which the param may be given a single time 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'). 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 The two different ways of specifying lists may not be mixed in
a single query string for the same parameter. a single query string for the same parameter.
Args: Args:
query_string (str): The query string to parse query_string (str): The query string to parse.
keep_blank_qs_values (bool): If set to True, preserves boolean fields keep_blank_qs_values (bool): If set to ``True``, preserves boolean
and fields with no content as blank strings. fields and fields with no content as blank strings.
Returns: Returns:
dict: A dict containing ``(name, value)`` tuples, one per query dict: A dictionary of (*name*, *value*) pairs, one per query
parameter. Note that *value* will be a string or list of parameter. Note that *value* may be a single ``str``, or a
strings. ``list`` of ``str``.
Raises: Raises:
TypeError: query_string was not a string or buffer TypeError: `query_string` was not a ``str``.
""" """
@@ -317,7 +317,7 @@ def parse_query_string(query_string, keep_blank_qs_values=False):
def parse_host(host, default_port=None): def parse_host(host, default_port=None):
"""Parse a canonical host:port string into parts. """Parse a canonical 'host:port' string into parts.
Parse a host string (which may or may not contain a port) into Parse a host string (which may or may not contain a port) into
parts, taking into account that the string may contain parts, taking into account that the string may contain
@@ -331,9 +331,9 @@ def parse_host(host, default_port=None):
the host string does not contain one (default ``None``). the host string does not contain one (default ``None``).
Returns: Returns:
tuple: A parsed (host, port) tuple from the given tuple: A parsed (*host*, *port*) tuple from the given
host string, with the port converted to an ``int``. host string, with the port converted to an ``int``.
If the string does not specify a port, `default_port` is If the host string does not specify a port, `default_port` is
used instead. used instead.
""" """