Routing

Routing is the process of matching and parsing a URL to something we can use. Pulsar provides a flexible integrated routing system you can use for that. It works by creating a Router instance with its own rule and, optionally, additional sub-routers for handling additional urls:

class Page(Router):
    response_content_types = RouterParam(('text/html',
                                          'text/plain',
                                          'application/json'))

    def get(self, request):
        "This method handle requests with get-method"
        ...

    def post(self, request):
        "This method handle requests with post-method"
        ...

    def delete(self, request):
        "This method handle requests with delete-method"
        ...

    ...


middleware = Page('/bla')

Router

The middleware constructed in the snippet above handles get and post methods at the /bla url. The Router introduces a new element into pulsar WSGI handlers, the wsgi request, a light-weight wrapper of the WSGI environ.

For an exhaustive example on how to use the Router middleware make sure you check out the HttpBin example.

class pulsar.apps.wsgi.routers.Router(rule, *routes, **parameters)[source]

A WSGI middleware to handle client requests on multiple routes.

The user must implement the HTTP methods required by the application. For example if the route needs to serve a GET request, the get(self, request) method must be implemented.

Parameters:
  • rule – String used for creating the route of this Router.
  • routes – Optional Router instances which are added to the children routes of this router.
  • parameters – Optional parameters for this router.
rule_methods

A class attribute built during class creation. It is an ordered dictionary mapping method names with a five-elements tuple containing information about a child route (See the route decorator).

routes

List of children Router of this Router.

parent

The parent Router of this Router.

response_content_types

A list/tuple of possible content types of a response to a client request.

The client request must accept at least one of the response content types, otherwise an HTTP 415 exception occurs.

response_wrapper

Optional function which wraps all handlers of this Router. The function must accept two parameters, the original handler and the WsgiRequest:

def response_wrapper(handler, request):
    ...
    return handler(request)
route

The relative Route served by this Router.

full_route

The full route for this Router.

It includes the parent portion of the route if a parent router is available.

root

The root Router for this Router.

creation_count

Integer for sorting Router by creation.

Auto-generated during initialisation.

rule

The full rule string for this Router.

It includes the parent portion of the rule if a parent router is available.

path(**urlargs)[source]

The full path of this Router.

It includes the parent portion of url if a parent router is available.

getparam(name, default=None, parents=False)[source]

A parameter in this Router

resolve(path, urlargs=None)[source]

Resolve a path and return a (handler, urlargs) tuple or None if the path could not be resolved.

response(environ, args)[source]

Once the resolve() method has matched the correct Router for serving the request, this matched router invokes this method to produce the WSGI response.

add_child(router, index=None)[source]

Add a new Router to the routes list.

remove_child(router)[source]

remove a Router from the routes list.

get_route(name)[source]

Get a child Router by its name.

This method search child routes recursively.

Return an anchor Html element with the href attribute set to the url of this Router.

has_parent(router)[source]

Check if router is self or a parent or self

make_router(rule, method=None, handler=None, cls=None, name=None, **params)[source]

Create a new Router from a rule and parameters.

This method is used during initialisation when building child Routers from the rule_methods.

Media Router

The MediaRouter is a specialised Router for serving static files such ass css, javascript, images and so forth.

class pulsar.apps.wsgi.routers.MediaRouter(rule, path=None, show_indexes=False, default_suffix=None, default_file='index.html', serve_only=None, **params)[source]

A Router for serving static media files from a given directory.

Parameters:
  • rute – The top-level url for this router. For example /media will serve the /media/<path:path> Route.
  • path – Check the path attribute.
  • show_indexes – Check the show_indexes attribute.
path

The file-system path of the media files to serve.

show_indexes

If True, the router will serve media file directories as well as media files.

serve_only

File suffixes to be served. When specified this is a set of suffixes (jpeg, png, json for example) which are served by this router if a file does not match the suffix it wont be served and the router return nothing so that other router can process the url.

default_file

The default file to serve when a directory is requested.

File Response

High level, battery included function for serving small and large files concurrently. Caveat, you app does not need to be asynchronous to use this method.

pulsar.apps.wsgi.routers.file_response(request, filepath, block=None, status_code=None, content_type=None, encoding=None, cache_control=None)[source]

Utility for serving a local file

Typical usage:

from pulsar.apps import wsgi

class MyRouter(wsgi.Router):

    def get(self, request):
        return wsgi.file_response(request, "<filepath>")
Parameters:
  • request – Wsgi request
  • filepath – full path of file to serve
  • block – Optional block size (default 1MB)
  • status_code – Optional status code (default 200)
Returns:

a WsgiResponse object

RouterParam

class pulsar.apps.wsgi.routers.RouterParam(value=None)[source]

A RouterParam is a way to flag a Router parameter so that children can inherit the value if they don’t define their own.

A RouterParam is always defined as a class attribute and it is processed by the Router metaclass and stored in a dictionary available as parameter class attribute.

value

The value associated with this RouterParam. This is the value stored in the Router.parameters dictionary at key given by the class attribute specified in the class definition.

Route rules

Routing classes for matching and parsing urls.

Note

The route module was originally from the routing module in werkzeug. Original License:

copyright (c) 2011 by the Werkzeug Team. License BSD

A Route is a class for relative url paths:

r1 = Route('bla')
r2 = Route('bla/foo')

Integers:

# accept any integer
Route('<int:size>')
# accept an integer between 1 and 200 only
Route('<int(min=1,max=200):size>')

Paths:

# accept any path (including slashes)
Route('<path:pages>')
Route('<path:pages>/edit')

Route decorator

class pulsar.apps.wsgi.route.route(rule=None, method=None, defaults=None, position=None, re=False, **parameters)[source]

Decorator to create a child route from a Router method.

Typical usage:

from pulsar.apps.wsgi import Router, route

class View(Router):

    def get(self, request):
        ...

    @route()
    def foo(self, request):
        ...

    @route('/bla', method='post')
    def handle2(self, request):
        ...

In this example, View is the parent router which handle get requests only.

The decorator injects the rule_method attribute to the method it decorates. The attribute is a five elements tuple which contains the Route, the HTTP method, a dictionary of additional parameters, position and the order. Position and order are internal integers used by the Router when deciding the order of url matching. If position is not passed, the order will be given by the position of each method in the Router class.

The decorated method are stored in the Router.rule_methods class attribute.

>>> len(View.rule_methods)
2
>>> View.rule_methods['foo'].rule
/foo
>>> View.rule_methods['foo'].method
'get'
>>> View.rule_methods['handle2'].rule
/bla
>>> View.rule_methods['handle2'].method
'post'

Check the HttpBin example for a sample usage.

Parameters:
  • rule – Optional string for the relative url served by the method which is decorated. If not supplied, the method name is used.
  • method – Optional HTTP method name. Default is get.
  • defaults – Optional dictionary of default variable values used when initialising the Route instance.
  • position – Optional positioning of the router within the list of child routers of the parent router
  • parameters – Additional parameters used when initialising the Router created by this decorator

Route

class pulsar.apps.wsgi.route.Route(rule, defaults=None, is_re=False)[source]

A Route is a class with a relative path.

Parameters:
  • rule – a normal URL path with placeholders in the format <converter(parameters):name> where both the converter and the parameters are optional. If no converter is defined the default converter is used which means string, name is the variable name.
  • defaults – optional dictionary of default values for the rule variables.
is_leaf

If True, the route is equivalent to a file. For example /bla/foo

rule

The rule string, does not include the initial '/'

path

The full rule for this route including initial '/'.

variables

a set of variable names for this route. If the route has no variables, the set is empty.

name

A nice name for the route.

Derived from rule replacing underscores and dashes.

ordered_variables

Tuple of ordered url variables

url(**urlargs)[source]

Build a url from urlargs key-value parameters

match(path)[source]

Match a path and return None if no matching, otherwise a dictionary of matched variables with values. If there is more to be match in the path, the remaining string is placed in the __remaining__ key of the dictionary.

split()[source]

Return a two element tuple containing the parent route and the last url bit as route. If this route is the root route, it returns the root route and None.