potpy.router – Router module

Module Contents

class potpy.router.Route(*handlers)[source]

A list of handlers which can be called with a Context.

Initializer can also be called with a single (non-tuple) iterable of handlers. Each handler item is either a callable or a tuple: (handler, name, exception_handlers) – see add() for details of this tuple.

__call__(context)[source]

Call the handlers in the route, in order, with the given context.

add(handler, name=None, exception_handlers=())[source]

Add a handler to the route.

Parameters:
  • handler – The “handler” callable to add.
  • name – Optional. When specified, the return value of this handler will be added to the context under name.
  • exception_handlers – Optional. A list of (types, handler) tuples, where types is an exception type (or tuple of types) to handle, and handler is a callable. See below for example.

Exception Handlers

When an exception occurs in a handler, exc_info will be temporarily added to the context and the list of exception handlers will be checked for an appropriate handler. If no handler can be found, the exception will be re-raised to the caller of the route.

If an appropriate exception handler is found, it will be called (the context will be injected, so handlers may take an exc_info argument), and its return value will be used in place of the original handler’s return value.

Examples:

>>> from potpy.context import Context
>>> route = Route()
>>> route.add(lambda: {}['foo'], exception_handlers=[
...     (KeyError, lambda: 'bar')
... ])
>>> route(Context())
'bar'
>>> def read_line_from_file():
...     raise IOError()     # simulate a failed read
...
>>> def retry_read():
...     return 'success!'   # simulate retrying the read
...
>>> def process_line(line):
...     return line.upper()
...
>>> route = Route()
>>> route.add(read_line_from_file, 'line', [
...     # return value will be added to context as 'line'
...     ((OSError, IOError), retry_read)
... ])
>>> route.add(process_line)
>>> route(Context())
'SUCCESS!'
>>> route = Route()
>>> route.add(lambda: {}['foo'], exception_handlers=[
...     (IndexError, lambda: 'bar') # does not handle KeyError
... ])
>>> route(Context())    # so exception will be re-raised here
Traceback (most recent call last):
    ...
KeyError: 'foo'
previous[source]

Refer to result of previous handler in route.

Example:

>>> from potpy.context import Context

>>> class MyClass:
...    def foo(self):
...        return 42
...
>>> route = Route(
...     MyClass,            # instantiate MyClass
...     Route.previous.foo  # refer to foo attribute of instance
... )
>>> route(Context())
42
context[source]

Refer to a context item in route.

Example:

>>> from potpy.context import Context

>>> class MyClass:
...     def foo(self):
...         return 42
...
>>> route = Route(
...     Route.context.inst.foo  # refer to ctx['inst'].foo
... )
>>> route(Context(inst=MyClass()))
42
exception Stop(value=<class 'potpy.router.NoValue'>)[source]

Raise this exception to jump out of a route early.

If an argument is provided, it will be used as the route return value, otherwise the return value of the previous handler will be returned.

Example::
>>> from potpy.context import Context
>>> def stopper():
...     raise Route.Stop('stops here')
...
>>> def foobar():
...     return 'never gets run'
...
>>> route = Route(stopper, foobar)
>>> route(Context())
'stops here'
class potpy.router.Router(*routes)[source]

Routes objects to handlers via a match() method.

When called with a Context and an object, that object will be checked against each registered handler for a match. When a matching handler is found, the context is updated with the result of the match() method, and the handler is called with the context.

Handlers are wrapped in Route objects, causing the context to be injected into the call. You may also add Route objects directly.

The match() method of this class is unimplemented. You must subclass it and provide an appropriate match method to define a Router. See potpy.wsgi.PathRouter and potpy.wsgi.MethodRouter for example subclasses.

__call__(context, obj)[source]

Route the given object to a matching handler.

Parameters:
  • context – The Context object used when calling the matching handler.
  • obj – The object to match against.
add(match, handler)[source]

Register a handler with the Router.

Parameters:
  • match – The first argument passed to the match() method when checking against this handler.
  • handler – A callable or Route instance that will handle matching calls. If not a Route instance, will be wrapped in one.
match(match, obj)[source]

Check for a match.

This method implements the routing logic of the Router. Handlers are registered with a match argument, which will be passed to this method when checking against that handler. When the Router is called with a context and an object, it will iterate over its list of registered handlers, passing the corresponding match argument and the object to this method once for each, until a match is found. If this method returns a dict, it signifies that the object matched against the current handler, and the context is updated with the returned dict. To signify a non-match, this method returns None, and iteration continues.

Note

This method is unimplemented in the base class. See potpy.wsgi.MethodRouter.match() for a concrete example.

Parameters:
  • match – The match argument corresponding to a handler registered with add().
  • obj – The object to match against.
Returns:

A dict or None.

Project Versions

Table Of Contents

Previous topic

potpy.context – Context module

Next topic

potpy.template – Template module

This Page