routes.mapper – Mapper and Sub-Mapper

Mapper and Sub-Mapper

Module Contents

class routes.mapper.SubMapperParent

Base class for Mapper and SubMapper, both of which may be the parent of SubMapper objects

collection(collection_name, resource_name, path_prefix=None, member_prefix='/{id}', controller=None, collection_actions=['index', 'create', 'new'], member_actions=['show', 'update', 'delete', 'edit'], member_options=None, **kwargs)

Create a submapper that represents a collection.

This results in a routes.mapper.SubMapper object, with a member property of the same type that represents the collection’s member resources.

Its interface is the same as the submapper together with member_prefix, member_actions and member_options which are passed to the member submapper as path_prefix, actions and keyword arguments respectively.


>>> from routes.util import url_for
>>> map = Mapper(controller_scan=None)
>>> c = map.collection('entries', 'entry')
>>>'ping', method='POST')
>>> url_for('entries') == '/entries'
>>> url_for('edit_entry', id=1) == '/entries/1/edit'
>>> url_for('ping_entry', id=1) == '/entries/1/ping'

Create a partial version of the Mapper with the designated options set

This results in a routes.mapper.SubMapper object.

If keyword arguments provided to this method also exist in the keyword arguments provided to the submapper, their values will be merged with the saved options going first.

In addition to routes.route.Route arguments, submapper can also take a path_prefix argument which will be prepended to the path of all routes that are connected.


>>> map = Mapper(controller_scan=None)
>>> map.connect('home', '/', controller='home', action='splash')
>>> map.matchlist[0].name == 'home'
>>> m = map.submapper(controller='home')
>>> m.connect('index', '/index', action='index')
>>> map.matchlist[1].name == 'index'
>>> map.matchlist[1].defaults['controller'] == 'home'

Optional collection_name and resource_name arguments are used in the generation of route names by the action and link methods. These in turn are used by the index, new, create, show, edit, update and delete methods which may be invoked indirectly by listing them in the actions argument. If the formatted argument is set to True (the default), generated paths are given the suffix ‘{.format}’ which matches or generates an optional format extension.


>>> from routes.util import url_for
>>> map = Mapper(controller_scan=None)
>>> m = map.submapper(path_prefix='/entries', collection_name='entries', resource_name='entry', actions=['index', 'new'])
>>> url_for('entries') == '/entries'
>>> url_for('new_entry', format='xml') == '/entries/new.xml'
class routes.mapper.SubMapper(obj, resource_name=None, collection_name=None, actions=None, formatted=None, **kwargs)

Partial mapper for use with_options

action(name=None, action=None, method='GET', formatted=None, **kwargs)

Generates a named route at the base path of a submapper.


>>> from routes import url_for
>>> map = Mapper(controller_scan=None)
>>> c = map.submapper(path_prefix='/entries', controller='entry')
>>> c.action(action='index', name='entries', formatted=True)
>>> c.action(action='create', method='POST')
>>> url_for(controller='entry', action='index', method='GET') == '/entries'
>>> url_for(controller='entry', action='index', method='GET', format='xml') == '/entries.xml'
>>> url_for(controller='entry', action='create', method='POST') == '/entries'
add_actions(actions, **kwargs)
connect(routename, path=None, **kwargs)

Generates the “create” action for a collection submapper.


Generates the “delete” action for a collection member submapper.


Generates the “edit” link for a collection member submapper.

index(name=None, **kwargs)

Generates the “index” action for a collection submapper.

Generates a named route for a subresource.


>>> from routes.util import url_for
>>> map = Mapper(controller_scan=None)
>>> c = map.collection('entries', 'entry')
>>>'recent', name='recent_entries')
>>>'ping', method='POST', formatted=True)
>>> url_for('entries') == '/entries'
>>> url_for('recent_entries') == '/entries/recent'
>>> url_for('ping_entry', id=1) == '/entries/1/ping'
>>> url_for('ping_entry', id=1, format='xml') == '/entries/1/ping.xml'

Generates the “new” link for a collection submapper.

show(name=None, **kwargs)

Generates the “show” action for a collection member submapper.


Generates the “update” action for a collection member submapper.

class routes.mapper.Mapper(controller_scan=<function controller_scan>, directory=None, always_scan=False, register=True, explicit=True)

Mapper handles URL generation and URL recognition in a web application.

Mapper is built handling dictionary’s. It is assumed that the web application will handle the dictionary returned by URL recognition to dispatch appropriately.

URL generation is done by passing keyword parameters into the generate function, a URL is then returned.

Create a new Mapper instance

All keyword arguments are optional.


Function reference that will be used to return a list of valid controllers used during URL matching. If directory keyword arg is present, it will be passed into the function during its call. This option defaults to a function that will scan a directory for controllers.

Alternatively, a list of controllers or None can be passed in which are assumed to be the definitive list of controller names valid when matching ‘controller’.

Passed into controller_scan for the directory to scan. It should be an absolute path if using the default controller_scan function.
Whether or not the controller_scan function should be run during every URL match. This is typically a good idea during development so the server won’t need to be restarted anytime a controller is added.
Boolean used to determine if the Mapper should use request_config to register itself as the mapper. Since it’s done on a thread-local basis, this is typically best used during testing though it won’t hurt in other cases.

Boolean used to determine if routes should be connected with implicit defaults of:


When set to True, these defaults will not be added to route connections and url_for will not use Route memory.

Additional attributes that may be set after mapper initialization (ie, map.ATTRIBUTE = ‘something’):

Used to indicate alternative encoding/decoding systems to use with both incoming URL’s, and during Route generation when passed a Unicode string. Defaults to ‘utf-8’.
How to handle errors in the encoding, generally ignoring any chars that don’t convert should be sufficient. Defaults to ‘ignore’.
Boolean used to indicate whether or not Routes should minimize URL’s and the generated URL’s, or require every part where it appears in the path. Defaults to False.
Whether or not Named Routes result in the default options for the route being used or if they actually force url generation to use the route. Defaults to False.
connect(*args, **kargs)

Create and connect a new Route to the Mapper.


m = Mapper()
m.connect('date/:year/:month/:day', controller="blog",
m.connect('archives/:page', controller="blog", action="by_page",
requirements = { 'page':'\d{1,2}' })
m.connect('category_list', 'archives/category/:section',
          controller='blog', action='category',
          section='home', type='list')
m.connect('home', '', controller='blog', action='view',
create_regs(*args, **kwargs)

Atomically creates regular expressions for all connected routes

extend(routes, path_prefix='')

Extends the mapper routes with a list of Route objects

If a path_prefix is provided, all the routes will have their path prepended with the path_prefix.


>>> map = Mapper(controller_scan=None)
>>> map.connect('home', '/', controller='home', action='splash')
>>> map.matchlist[0].name == 'home'
>>> routes = [Route('index', '/index.htm', controller='home',
...                 action='index')]
>>> map.extend(routes)
>>> len(map.matchlist) == 2
>>> map.extend(routes, path_prefix='/subapp')
>>> len(map.matchlist) == 3
>>> map.matchlist[2].routepath == '/subapp/index.htm'


This function does not merely extend the mapper with the given list of routes, it actually creates new routes with identical calling arguments.

generate(*args, **kargs)

Generate a route from a set of keywords

Returns the url text, or None if no URL could be generated.

make_route(*args, **kargs)

Make a new Route object

A subclass can override this method to use a custom Route class.

match(url=None, environ=None)

Match a URL against against one of the routes contained.

Will return None if no valid match is found.

resultdict = m.match('/joe/sixpack')
redirect(match_path, destination_path, *args, **kwargs)

Add a redirect route to the mapper

Redirect routes bypass the wrapped WSGI application and instead result in a redirect being issued by the RoutesMiddleware. As such, this method is only meaningful when using RoutesMiddleware.

By default, a 302 Found status code is used, this can be changed by providing a _redirect_code keyword argument which will then be used instead. Note that the entire status code string needs to be present.

When using keyword arguments, all arguments that apply to matching will be used for the match, while generation specific options will be used during generation. Thus all options normally available to connected Routes may be used with redirect routes as well.


map = Mapper()
map.redirect('/legacyapp/archives/{url:.*}', '/archives/{url}')
map.redirect('/home/index', '/',
             _redirect_code='301 Moved Permanently')
resource(member_name, collection_name, **kwargs)

Generate routes for a controller resource

The member_name name should be the appropriate singular version of the resource given your locale and used with members of the collection. The collection_name name will be used to refer to the resource collection methods and should be a plural version of the member_name argument. By default, the member_name name will also be assumed to map to a controller you create.

The concept of a web resource maps somewhat directly to ‘CRUD’ operations. The overlying things to keep in mind is that mapping a resource is about handling creating, viewing, and editing that resource.

All keyword arguments are optional.

If specified in the keyword args, the controller will be the actual controller used, but the rest of the naming conventions used for the route names and URL paths are unchanged.

Additional action mappings used to manipulate/view the entire set of resources provided by the controller.


map.resource('message', 'messages', collection={'rss':'GET'})
# GET /message/rss (maps to the rss action)
# also adds named route "rss_message"

Additional action mappings used to access an individual ‘member’ of this controllers resources.


map.resource('message', 'messages', member={'mark':'POST'})
# POST /message/1/mark (maps to the mark action)
# also adds named route "mark_message"

Action mappings that involve dealing with a new member in the controller resources.


map.resource('message', 'messages', new={'preview':'POST'})
# POST /message/new/preview (maps to the preview action)
# also adds a url named "preview_new_message"
Prepends the URL path for the Route with the path_prefix given. This is most useful for cases where you want to mix resources or relations between resources.

Perpends the route names that are generated with the name_prefix given. Combined with the path_prefix option, it’s easy to generate route names and paths that represent resources that are in relations.


map.resource('message', 'messages', controller='categories',
# GET /category/7/message/1
# has named route "category_message"


A dictionary that restricts the matching of a variable. Can be used when matching variables with path_prefix.


map.resource('message', 'messages',
     requirements={"project_id": R"\d+"})
# POST /01234/message
#    success, project_id is set to "01234"
# POST /foo/message
#    404 not found, won't be matched by this route

A dict containing information about the parent resource, for creating a nested resource. It should contain the member_name and collection_name of the parent resource. This dict will be available via the associated Route object which can be accessed during a request via request.environ['routes.route']

If parent_resource is supplied and path_prefix isn’t, path_prefix will be generated from parent_resource as “<parent collection name>/:<parent member name>_id”.

If parent_resource is supplied and name_prefix isn’t, name_prefix will be generated from parent_resource as “<parent member name>_”.


>>> from routes.util import url_for
>>> m = Mapper()
>>> m.resource('location', 'locations',
...            parent_resource=dict(member_name='region',
...                                 collection_name='regions'))
>>> # path_prefix is "regions/:region_id"
>>> # name prefix is "region_"
>>> url_for('region_locations', region_id=13)
>>> url_for('region_new_location', region_id=13)
>>> url_for('region_location', region_id=13, id=60)
>>> url_for('region_edit_location', region_id=13, id=60)

Overriding generated path_prefix:

>>> m = Mapper()
>>> m.resource('location', 'locations',
...            parent_resource=dict(member_name='region',
...                                 collection_name='regions'),
...            path_prefix='areas/:area_id')
>>> # name prefix is "region_"
>>> url_for('region_locations', area_id=51)

Overriding generated name_prefix:

>>> m = Mapper()
>>> m.resource('location', 'locations',
...            parent_resource=dict(member_name='region',
...                                 collection_name='regions'),
...            name_prefix='')
>>> # path_prefix is "regions/:region_id"
>>> url_for('locations', region_id=51)
routematch(url=None, environ=None)

Match a URL against against one of the routes contained.

Will return None if no valid match is found, otherwise a result dict and a route object is returned.

resultdict, route_obj = m.match('/joe/sixpack')