API Documentation

Resource routing

URL routing for Twisted Web resources.

A Python-based Domain Specific Language is used to specify and match routing paths, string literal components are matched for structure while plain callable components match segment values and are stored by name for use in the handler, assuming all the components match; this makes it trivial to create new functions to match path components.

route is used to match a URL exactly (the number of route components must match the number of URL path segments) while subroute is used to match a URL prefix (the specified route components must match the respective segments in a URL path, additional segments are used in child resource location as normal.)

Router is an IResource that allows decorating methods as route or subroute handlers.

Members

class txspinneret.route.Router[source]

Bases: object

URL routing.

Router is designed to be used as a Python descriptor using Router.route or Router.subroute to decorate route handlers, for example:

class Users(object):
    router = Router()

    @router.route('name')
    def name(self, request, params):
        # ...

Route handlers can return any value supported by ISpinneretResource.locateChild.

Calling Router.resource will produce an IResource.

__weakref__

list of weak references to the object (if defined)

resource()[source]

Create an IResource that will perform URL routing.

route(*components)[source]

See txspinneret.route.route.

This decorator can be stacked with itself to specify multiple routes with a single handler.

subroute(*components)[source]

See txspinneret.route.subroute.

This decorator can be stacked with itself to specify multiple routes with a single handler.

txspinneret.route.Any(name, encoding=None)

Match a route parameter.

Any is a synonym for Text.

Parameters:
  • name (bytes) – Route parameter name.
  • encoding (bytes) – Default encoding to assume if the Content-Type header is lacking one.
Returns:

callable suitable for use with route or subroute.

txspinneret.route.Text(name, encoding=None)[source]

Match a route parameter.

Any is a synonym for Text.

Parameters:
  • name (bytes) – Route parameter name.
  • encoding (bytes) – Default encoding to assume if the Content-Type header is lacking one.
Returns:

callable suitable for use with route or subroute.

txspinneret.route.Integer(name, base=10, encoding=None)[source]

Match an integer route parameter.

Parameters:
  • name (bytes) – Route parameter name.
  • base (int) – Base to interpret the value in.
  • encoding (bytes) – Default encoding to assume if the Content-Type header is lacking one.
Returns:

callable suitable for use with route or subroute.

txspinneret.route.route(*components)[source]

Match a request path exactly.

The path components are always matched relative to their parent is in the resource hierarchy, in other words it is only possible to match URIs nested more deeply than the parent resource.

Parameters:components (iterable of bytes or callable) – Iterable of path components, to match against the request, either static strings or dynamic parameters. As a convenience, a single bytes component containing / may be given instead of manually separating the components. If no components are given the null route is matched, this is the case where segments is empty.
Return type:2-tuple of dict keyed on bytes and list of bytes
Returns:Pair of parameter results, mapping parameter names to processed values, and a list of the remaining request path segments. If there is no route match the result will be None and the original request path segments.
txspinneret.route.subroute(*components)[source]

Partially match a request path exactly.

The path components are always matched relative to their parent is in the resource hierarchy, in other words it is only possible to match URIs nested more deeply than the parent resource.

If there are more request path segments than components the match may still be successful, the remaining path segments are returned in the second part of the result.

Parameters:components (iterable of bytes or callable) – Iterable of path components, to match against the request, either static strings or dynamic parameters. As a convenience, a single bytes component containing / may be given instead of manually separating the components. If no components are given the null route is matched, this is the case where segments is empty.
Return type:2-tuple of dict keyed on bytes and list of bytes
Returns:Pair of parameter results, mapping parameter names to processed values, and a list of the remaining request path segments. If there is no route match the result will be None and the original request path segments.

Query arguments

Utility functions for processing query arguments.

The task of processing query arguments is made easy by deciding whether you want exactly one or many results and then composing that with the expected argument type, such as Integer, Text, Boolean, etc.; for example:

one(Integer)

Produces a callable that takes a list of strings and produces an integer from the first value, or None if the list was empty or the first value could not be parsed as an integer.

many(Boolean)

Produces a callable that takes a list of strings and produces a list of booleans.

Members

txspinneret.query.parse(expected, query)[source]

Parse query parameters.

Parameters:
  • expected (dict mapping bytes to callable) – Mapping of query argument names to argument parsing callables.
  • query (dict mapping bytes to list of bytes) – Mapping of query argument names to lists of argument values, this is the form that Twisted Web’s IRequest.args value takes.
Return type:

dict mapping bytes to object

Returns:

Mapping of query argument names to parsed argument values.

txspinneret.query.one(func, n=0)[source]

Create a callable that applies func to a value in a sequence.

If the value is not a sequence or is an empty sequence then None is returned.

Parameters:
  • func (callable) – Callable to be applied to each result.
  • n (int) – Index of the value to apply func to.
txspinneret.query.many(func)[source]

Create a callable that applies func to every value in a sequence.

If the value is not a sequence then an empty list is returned.

Parameters:func (callable) – Callable to be applied to the first result.
txspinneret.query.Text(value, encoding=None)[source]

Parse a value as text.

Parameters:
  • value (unicode or bytes) – Text value to parse
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

unicode

Returns:

Parsed text or None if value is neither bytes nor unicode.

txspinneret.query.Integer(value, base=10, encoding=None)[source]

Parse a value as an integer.

Parameters:
  • value (unicode or bytes) – Text value to parse
  • base (unicode or bytes) – Base to assume value is specified in.
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

int

Returns:

Parsed integer or None if value could not be parsed as an integer.

txspinneret.query.Float(value, encoding=None)[source]

Parse a value as a floating point number.

Parameters:
  • value (unicode or bytes) – Text value to parse.
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

float

Returns:

Parsed float or None if value could not be parsed as a float.

txspinneret.query.Boolean(value, true=(u'yes', u'1', u'true'), false=(u'no', u'0', u'false'), encoding=None)[source]

Parse a value as a boolean.

Parameters:
  • value (unicode or bytes) – Text value to parse.
  • true (tuple of unicode) – Values to compare, ignoring case, for True values.
  • false (tuple of unicode) – Values to compare, ignoring case, for False values.
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

bool

Returns:

Parsed boolean or None if value did not match true or false values.

txspinneret.query.Delimited(value, parser=<function Text at 0x3ca1a28>, delimiter=u', ', encoding=None)[source]

Parse a value as a delimited list.

Parameters:
  • value (unicode or bytes) – Text value to parse.
  • parser (callable taking a unicode parameter) – Callable to map over the delimited text values.
  • delimiter (unicode) – Delimiter text.
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

list

Returns:

List of parsed values.

txspinneret.query.Timestamp(value, _divisor=1.0, tz=FixedOffset(0, 0), encoding=None)[source]

Parse a value as a POSIX timestamp in seconds.

Parameters:
  • value (unicode or bytes) – Text value to parse, which should be the number of seconds since the epoch.
  • _divisor (float) – Number to divide the value by.
  • tz (tzinfo) – Timezone, defaults to UTC.
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

datetime.datetime

Returns:

Parsed datetime or None if value could not be parsed.

txspinneret.query.TimestampMs(value, encoding=None)[source]

Parse a value as a POSIX timestamp in milliseconds.

Parameters:
  • value (unicode or bytes) – Text value to parse, which should be the number of milliseconds since the epoch.
  • encoding (bytes) – Encoding to treat bytes values as, defaults to utf-8.
Return type:

datetime.datetime

Returns:

Parsed datetime or None if value could not be parsed.

Utility resources

A collection of higher-level Twisted Web resources, suitable for use with any existing IResource implementations.

SpinneretResource adapts an ISpinneretResource to IResource.

ContentTypeNegotiator will negotiate a resource based on the Accept header.

Members

class txspinneret.resource.SpinneretResource(wrappedResource)[source]

Bases: twisted.web.resource.Resource

Adapter from ISpinneretResource to IResource.

Parameters:wrappedResource (ISpinneretResource) – Spinneret resource to wrap in an IResource.
class txspinneret.resource.ContentTypeNegotiator(handlers, fallback=False)[source]

Bases: twisted.web.resource.Resource

Negotiate an appropriate representation based on the Accept header.

Rendering this resource will negotiate a representation and render the matching handler.

Parameters:
  • handlers (iterable of INegotiableResource and either IResource or ISpinneretResource.) – Iterable of negotiable resources, either ISpinneretResource or IResource, to use as handlers for negotiation.
  • fallback (bool) – Fall back to the first handler in the case where negotiation fails?
class txspinneret.resource.NotAcceptable[source]

Bases: twisted.web.resource.Resource

Leaf resource that renders an empty body for 406 Not Acceptable.

Initialize.

class txspinneret.resource.NotFound[source]

Bases: twisted.web.resource.NoResource

Leaf resource that renders a page for 404 Not Found.

Interfaces

interface txspinneret.interfaces.INegotiableResource[source]

Bases: zope.interface.Interface

Resource used for content negotiation.

The implementation should be adaptable to IResource.

acceptTypes = <zope.interface.interface.Attribute object at 0x422ad90>

list of bytes indicating the content types this resource is capable of accepting.

contentType = <zope.interface.interface.Attribute object at 0x422ad10>

bytes indicating the content type of this resource when rendered.

interface txspinneret.interfaces.ISpinneretResource[source]

Bases: zope.interface.Interface

Spinneret resource.

Spinneret resources may additionally have methods like render_GET (to handle a GET request) render_POST etc., like IResource, that may return the same types of objects as ISpinneretResource.locateChild.

Adaptable to IResource.

locateChild(request, segments)[source]

Locate another object which can be adapted to IResource.

Parameters:
  • request (IRequest) – Request.
  • segments (sequence of bytes) – Sequence of strings giving the remaining query segments to resolve.
Return type:

2-tuple of IResource, IRenderable or URLPath and a sequence of bytes

Returns:

Pair of an IResource, IRenderable or URLPath and a sequence of the remaining path segments to be process, or a Deferred containing the aforementioned result.