Skip to content

Commit

Permalink
Doc updates, modules N-T.
Browse files Browse the repository at this point in the history
  • Loading branch information
bdarnell committed Mar 16, 2013
1 parent c11f8d0 commit 693ebbe
Show file tree
Hide file tree
Showing 7 changed files with 129 additions and 134 deletions.
23 changes: 12 additions & 11 deletions tornado/netutil.py
Expand Up @@ -41,14 +41,14 @@ def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=128, flags
Address may be either an IP address or hostname. If it's a hostname, Address may be either an IP address or hostname. If it's a hostname,
the server will listen on all IP addresses associated with the the server will listen on all IP addresses associated with the
name. Address may be an empty string or None to listen on all name. Address may be an empty string or None to listen on all
available interfaces. Family may be set to either socket.AF_INET available interfaces. Family may be set to either `socket.AF_INET`
or socket.AF_INET6 to restrict to ipv4 or ipv6 addresses, otherwise or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
both will be used if available. both will be used if available.
The ``backlog`` argument has the same meaning as for The ``backlog`` argument has the same meaning as for
``socket.listen()``. `socket.listen() <socket.socket.listen>`.
``flags`` is a bitmask of AI_* flags to ``getaddrinfo``, like ``flags`` is a bitmask of AI_* flags to `~socket.getaddrinfo`, like
``socket.AI_PASSIVE | socket.AI_NUMERICHOST``. ``socket.AI_PASSIVE | socket.AI_NUMERICHOST``.
""" """
sockets = [] sockets = []
Expand Down Expand Up @@ -119,13 +119,13 @@ def bind_unix_socket(file, mode=0o600, backlog=128):




def add_accept_handler(sock, callback, io_loop=None): def add_accept_handler(sock, callback, io_loop=None):
"""Adds an ``IOLoop`` event handler to accept new connections on ``sock``. """Adds an `.IOLoop` event handler to accept new connections on ``sock``.
When a connection is accepted, ``callback(connection, address)`` will When a connection is accepted, ``callback(connection, address)`` will
be run (``connection`` is a socket object, and ``address`` is the be run (``connection`` is a socket object, and ``address`` is the
address of the other end of the connection). Note that this signature address of the other end of the connection). Note that this signature
is different from the ``callback(fd, events)`` signature used for is different from the ``callback(fd, events)`` signature used for
``IOLoop`` handlers. `.IOLoop` handlers.
""" """
if io_loop is None: if io_loop is None:
io_loop = IOLoop.current() io_loop = IOLoop.current()
Expand Down Expand Up @@ -192,10 +192,10 @@ def resolve(self, host, port, family=socket.AF_UNSPEC, callback=None):
Returns a `~concurrent.futures.Future` whose result is a list Returns a `~concurrent.futures.Future` whose result is a list
of (family, address) pairs, where address is a tuple suitable of (family, address) pairs, where address is a tuple suitable
to pass to `socket.socket.connect` (i.e. a (host, port) pair for to pass to `socket.connect <socket.socket.connect>` (i.e. a
IPv4; additional fields may be present for IPv6). If a ``(host, port)`` pair for IPv4; additional fields may be
callback is passed, it will be run with the result as an present for IPv6). If a ``callback`` is passed, it will be run
argument when it is complete. with the result as an argument when it is complete.
""" """
raise NotImplementedError() raise NotImplementedError()


Expand Down Expand Up @@ -270,7 +270,8 @@ def resolve(self, host, port, *args, **kwargs):




def ssl_options_to_context(ssl_options): def ssl_options_to_context(ssl_options):
"""Try to Convert an ssl_options dictionary to an SSLContext object. """Try to convert an ``ssl_options`` dictionary to an
`~ssl.SSLContext` object.
The ``ssl_options`` dictionary contains keywords to be passed to The ``ssl_options`` dictionary contains keywords to be passed to
`ssl.wrap_socket`. In Python 3.2+, `ssl.SSLContext` objects can `ssl.wrap_socket`. In Python 3.2+, `ssl.SSLContext` objects can
Expand Down
42 changes: 23 additions & 19 deletions tornado/options.py
Expand Up @@ -29,27 +29,28 @@ def connect():
db = database.Connection(options.mysql_host) db = database.Connection(options.mysql_host)
... ...
The main() method of your application does not need to be aware of all of The ``main()`` method of your application does not need to be aware of all of
the options used throughout your program; they are all automatically loaded the options used throughout your program; they are all automatically loaded
when the modules are loaded. However, all modules that define options when the modules are loaded. However, all modules that define options
must have been imported before the command line is parsed. must have been imported before the command line is parsed.
Your main() method can parse the command line or parse a config file with Your ``main()`` method can parse the command line or parse a config file with
either:: either::
tornado.options.parse_command_line() tornado.options.parse_command_line()
# or # or
tornado.options.parse_config_file("/etc/server.conf") tornado.options.parse_config_file("/etc/server.conf")
Command line formats are what you would expect ("--myoption=myvalue"). Command line formats are what you would expect (``--myoption=myvalue``).
Config files are just Python files. Global names become options, e.g.:: Config files are just Python files. Global names become options, e.g.::
myoption = "myvalue" myoption = "myvalue"
myotheroption = "myothervalue" myotheroption = "myothervalue"
We support datetimes, timedeltas, ints, and floats (just pass a 'type' We support `datetimes <datetime.datetime>`, `timedeltas
kwarg to define). We also accept multi-value options. See the documentation <datetime.timedelta>`, ints, and floats (just pass a ``type`` kwarg to
for define() below. `define`). We also accept multi-value options. See the documentation for
`define()` below.
`tornado.options.options` is a singleton instance of `OptionParser`, and `tornado.options.options` is a singleton instance of `OptionParser`, and
the top-level functions in this module (`define`, `parse_command_line`, etc) the top-level functions in this module (`define`, `parse_command_line`, etc)
Expand Down Expand Up @@ -103,28 +104,29 @@ def define(self, name, default=None, type=None, help=None, metavar=None,
multiple=False, group=None, callback=None): multiple=False, group=None, callback=None):
"""Defines a new command line option. """Defines a new command line option.
If type is given (one of str, float, int, datetime, or timedelta) If ``type`` is given (one of str, float, int, datetime, or timedelta)
or can be inferred from the default, we parse the command line or can be inferred from the ``default``, we parse the command line
arguments based on the given type. If multiple is True, we accept arguments based on the given type. If ``multiple`` is True, we accept
comma-separated values, and the option value is always a list. comma-separated values, and the option value is always a list.
For multi-value integers, we also accept the syntax x:y, which For multi-value integers, we also accept the syntax ``x:y``, which
turns into range(x, y) - very useful for long integer ranges. turns into ``range(x, y)`` - very useful for long integer ranges.
help and metavar are used to construct the automatically generated ``help`` and ``metavar`` are used to construct the
command line help string. The help message is formatted like:: automatically generated command line help string. The help
message is formatted like::
--name=METAVAR help string --name=METAVAR help string
group is used to group the defined options in logical ``group`` is used to group the defined options in logical
groups. By default, command line options are grouped by the groups. By default, command line options are grouped by the
file in which they are defined. file in which they are defined.
Command line option names must be unique globally. They can be parsed Command line option names must be unique globally. They can be parsed
from the command line with parse_command_line() or parsed from a from the command line with `parse_command_line` or parsed from a
config file with parse_config_file. config file with `parse_config_file`.
If a callback is given, it will be run with the new value whenever If a ``callback`` is given, it will be run with the new value whenever
the option is changed. This can be used to combine command-line the option is changed. This can be used to combine command-line
and file-based options:: and file-based options::
Expand Down Expand Up @@ -159,9 +161,11 @@ def define(self, name, default=None, type=None, help=None, metavar=None,
callback=callback) callback=callback)


def parse_command_line(self, args=None, final=True): def parse_command_line(self, args=None, final=True):
"""Parses all options given on the command line (defaults to sys.argv). """Parses all options given on the command line (defaults to
`sys.argv`).
Note that args[0] is ignored since it is the program name in sys.argv. Note that ``args[0]`` is ignored since it is the program name
in `sys.argv`.
We return a list of all arguments that are not parsed as options. We return a list of all arguments that are not parsed as options.
Expand Down
10 changes: 6 additions & 4 deletions tornado/process.py
Expand Up @@ -14,7 +14,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.


"""Utilities for working with multiple processes.""" """Utilities for working with multiple processes, including both forking
the server into multiple processes and managing subprocesses.
"""


from __future__ import absolute_import, division, print_function, with_statement from __future__ import absolute_import, division, print_function, with_statement


Expand Down Expand Up @@ -229,10 +231,10 @@ def set_exit_callback(self, callback):
def initialize(cls, io_loop=None): def initialize(cls, io_loop=None):
"""Initializes the ``SIGCHILD`` handler. """Initializes the ``SIGCHILD`` handler.
The signal handler is run on an IOLoop to avoid locking issues. The signal handler is run on an `.IOLoop` to avoid locking issues.
Note that the IOLoop used for signal handling need not be the Note that the `.IOLoop` used for signal handling need not be the
same one used by individual Subprocess objects (as long as the same one used by individual Subprocess objects (as long as the
IOLoops are each running in separate threads). ``IOLoops`` are each running in separate threads).
""" """
if cls._initialized: if cls._initialized:
return return
Expand Down
33 changes: 17 additions & 16 deletions tornado/stack_context.py
Expand Up @@ -14,20 +14,21 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.


"""StackContext allows applications to maintain threadlocal-like state """`StackContext` allows applications to maintain threadlocal-like state
that follows execution as it moves to other execution contexts. that follows execution as it moves to other execution contexts.
The motivating examples are to eliminate the need for explicit The motivating examples are to eliminate the need for explicit
async_callback wrappers (as in tornado.web.RequestHandler), and to ``async_callback`` wrappers (as in `tornado.web.RequestHandler`), and to
allow some additional context to be kept for logging. allow some additional context to be kept for logging.
This is slightly magic, but it's an extension of the idea that an exception This is slightly magic, but it's an extension of the idea that an
handler is a kind of stack-local state and when that stack is suspended exception handler is a kind of stack-local state and when that stack
and resumed in a new context that state needs to be preserved. StackContext is suspended and resumed in a new context that state needs to be
shifts the burden of restoring that state from each call site (e.g. preserved. `StackContext` shifts the burden of restoring that state
wrapping each AsyncHTTPClient callback in async_callback) to the mechanisms from each call site (e.g. wrapping each `.AsyncHTTPClient` callback
that transfer control from one context to another (e.g. AsyncHTTPClient in ``async_callback``) to the mechanisms that transfer control from
itself, IOLoop, thread pools, etc). one context to another (e.g. `.AsyncHTTPClient` itself, `.IOLoop`,
thread pools, etc).
Example usage:: Example usage::
Expand Down Expand Up @@ -151,11 +152,11 @@ def __exit__(self, type, value, traceback):
class ExceptionStackContext(object): class ExceptionStackContext(object):
"""Specialization of StackContext for exception handling. """Specialization of StackContext for exception handling.
The supplied exception_handler function will be called in the The supplied ``exception_handler`` function will be called in the
event of an uncaught exception in this context. The semantics are event of an uncaught exception in this context. The semantics are
similar to a try/finally clause, and intended use cases are to log similar to a try/finally clause, and intended use cases are to log
an error, close a socket, or similar cleanup actions. The an error, close a socket, or similar cleanup actions. The
exc_info triple (type, value, traceback) will be passed to the ``exc_info`` triple ``(type, value, traceback)`` will be passed to the
exception_handler function. exception_handler function.
If the exception handler returns true, the exception will be If the exception handler returns true, the exception will be
Expand Down Expand Up @@ -188,11 +189,11 @@ def __exit__(self, type, value, traceback):




class NullContext(object): class NullContext(object):
"""Resets the StackContext. """Resets the `StackContext`.
Useful when creating a shared resource on demand (e.g. an AsyncHTTPClient) Useful when creating a shared resource on demand (e.g. an
where the stack that caused the creating is not relevant to future `.AsyncHTTPClient`) where the stack that caused the creating is
operations. not relevant to future operations.
""" """
def __enter__(self): def __enter__(self):
self.old_contexts = _state.contexts self.old_contexts = _state.contexts
Expand All @@ -207,7 +208,7 @@ class _StackContextWrapper(functools.partial):




def wrap(fn): def wrap(fn):
"""Returns a callable object that will restore the current StackContext """Returns a callable object that will restore the current `StackContext`
when executed. when executed.
Use this whenever saving a callback to be executed later in a Use this whenever saving a callback to be executed later in a
Expand Down
9 changes: 4 additions & 5 deletions tornado/tcpserver.py
Expand Up @@ -35,7 +35,6 @@ class TCPServer(object):
To use `TCPServer`, define a subclass which overrides the `handle_stream` To use `TCPServer`, define a subclass which overrides the `handle_stream`
method. method.
`TCPServer` can serve SSL traffic with Python 2.6+ and OpenSSL.
To make this server serve SSL traffic, send the ssl_options dictionary To make this server serve SSL traffic, send the ssl_options dictionary
argument with the arguments required for the `ssl.wrap_socket` method, argument with the arguments required for the `ssl.wrap_socket` method,
including "certfile" and "keyfile":: including "certfile" and "keyfile"::
Expand Down Expand Up @@ -145,12 +144,12 @@ def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128):
Address may be either an IP address or hostname. If it's a hostname, Address may be either an IP address or hostname. If it's a hostname,
the server will listen on all IP addresses associated with the the server will listen on all IP addresses associated with the
name. Address may be an empty string or None to listen on all name. Address may be an empty string or None to listen on all
available interfaces. Family may be set to either ``socket.AF_INET`` available interfaces. Family may be set to either `socket.AF_INET`
or ``socket.AF_INET6`` to restrict to ipv4 or ipv6 addresses, otherwise or `socket.AF_INET6` to restrict to IPv4 or IPv6 addresses, otherwise
both will be used if available. both will be used if available.
The ``backlog`` argument has the same meaning as for The ``backlog`` argument has the same meaning as for
`socket.socket.listen`. `socket.listen <socket.socket.listen>`.
This method may be called multiple times prior to `start` to listen This method may be called multiple times prior to `start` to listen
on multiple ports or interfaces. on multiple ports or interfaces.
Expand All @@ -163,7 +162,7 @@ def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128):
self._pending_sockets.extend(sockets) self._pending_sockets.extend(sockets)


def start(self, num_processes=1): def start(self, num_processes=1):
"""Starts this server in the IOLoop. """Starts this server in the `.IOLoop`.
By default, we run the server in this process and do not fork any By default, we run the server in this process and do not fork any
additional child process. additional child process.
Expand Down
18 changes: 7 additions & 11 deletions tornado/template.py
Expand Up @@ -299,14 +299,14 @@ def _get_ancestors(self, loader):




class BaseLoader(object): class BaseLoader(object):
"""Base class for template loaders.""" """Base class for template loaders.
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None):
"""Creates a template loader.
root_directory may be the empty string if this loader does not
use the filesystem.
autoescape must be either None or a string naming a function You must use a template loader to use template constructs like
``{% extends %}`` and ``{% include %}``. The loader caches all
templates after they are loaded the first time.
"""
def __init__(self, autoescape=_DEFAULT_AUTOESCAPE, namespace=None):
"""``autoescape`` must be either None or a string naming a function
in the template namespace, such as "xhtml_escape". in the template namespace, such as "xhtml_escape".
""" """
self.autoescape = autoescape self.autoescape = autoescape
Expand Down Expand Up @@ -342,10 +342,6 @@ def _create_template(self, name):


class Loader(BaseLoader): class Loader(BaseLoader):
"""A template loader that loads from a single root directory. """A template loader that loads from a single root directory.
You must use a template loader to use template constructs like
{% extends %} and {% include %}. Loader caches all templates after
they are loaded the first time.
""" """
def __init__(self, root_directory, **kwargs): def __init__(self, root_directory, **kwargs):
super(Loader, self).__init__(**kwargs) super(Loader, self).__init__(**kwargs)
Expand Down

0 comments on commit 693ebbe

Please sign in to comment.