URL dispatch

Pesto’s DispatcherApp is a useful WSGI application that can map URIs to handler functions. For example:

from pesto import DispatcherApp, Response
app = DispatcherApp()

@app.match('/recipes', 'GET')
def recipe_index(request):
        return Response(['This is the recipe index page'])

@app.match('/recipes/<category:unicode>', 'GET')
def recipe_index(request, category):
        return Response(['This is the page for ', category, ' recipes'])

Dispatchers can use prefined patterns expressions to extract data from URIs and pass it on to a handler. The following expression types are supported:

  • unicode - any unicode string (not including forward slashes)
  • path - any path (includes forward slashes)
  • int - any integer
  • any - a string matching a list of alternatives

It is also possible to add your own types so you to match custom patterns (see the API documentation for ExtensiblePattern.register_pattern). Match patterns are delimited by angle brackets, and generally have the form <name:type>. Some examples:

  • '/recipes/<category:unicode>/<id:int>'. This would match a URI such as /recipes/fish/7, and call the handler function with the arguments category=u'fish', id=7.
  • '/entries/<year:int>/<month:int>. This would match a URI such as /entries/2008/05, and call the handler function with the arguments year=2008, month=5.
  • '/documents/<directory:path>/<name:unicode>.pdf. This would match a URI such as /documents/all/2008/topsecret.pdf, and call the handler function with the arguments directory=u'all/2008/', name=u'topsecret'.

You can also map separate handlers to different HTTP methods for the same URL, eg the GET method could display a form, and the POST method of the same URL could handle the submission:

@app.match('/contact-form', 'GET')
def contact_form(request):
    Display a contact form

@app.match('/contact-form', 'POST')
def contact_form_submit(request):
    Process the form, eg by sending an email

Dispatchers do not have to be function decorators. The following code is equivalent to the previous example:

app.match('/contact-form', GET=contact_form, POST=contact_form_submit)

Matching is always based on the path part of the URL (taken from the WSGI environ['PATH_INFO'] value).

URI redirecting

A combination of the Response object and dispatchers can be used for URI rewriting and redirection:

from functools import partial

from pesto import DispatcherApp, Response
from pesto import response

app = DispatcherApp()
app.match('/old-link', GET=partial(Response.redirect, '/new-link', status=response.STATUS_MOVED_PERMANENTLY))

Any calls to /old-link will now be met with:

301 Moved Permanently
Content-Type: text/html; charset=UTF-8
Location: http://localhost/new-link

URI generation

Functions mapped by the dispatcher object are assigned a url method, allowing URIs to be generated:

from pesto import DispatcherApp, Response

app = DispatcherApp()
@app.match('/recipes', 'GET')
def recipe_index(request):
        return Response(['this is the recipe index page'])

@app.match('/recipes/<recipe_id:int>', 'GET')
def show_recipe(request, recipe_id):
        return Response(['this is the recipe detail page for recipe #%d' % recipe_id])

Calling the url method will generate fully qualified URLs for any function mapped by a dispatcher:

>>> from pesto.testing import make_environ
>>> from pesto.request import Request
>>> request = Request(make_environ(SERVER_NAME='example.com'))
>>> recipe_index.url()
>>> show_recipe.url(recipe_id=42)

Note: the url method needs a live request object, usually acquired through pesto.currentrequest, although it can also be passed as a parameter. If you need to call this method outside of a WSGI request context then you will need to simulate a WSGI environ to generate a Request object.

Repurposing handler functions

Suppose you have a function that returns a list of orders, with the price and date, and you want to this list both as regular HTML page and in JSON notation for AJAX enhancement. Instead of writing two handlers – one for the HTML response and one for the JSON – it’s possible to use the same handler function to serve both types of request.

We’ll start by creating some sample data:

from datetime import date

class Order(object):

    def __init__(self, price, date):
            self.price = price
            self.date = date

orders = [
    Order(12.99, date(2009, 7, 1)),
    Order(7.75, date(2009, 8, 1)),
    Order(8.25, date(2009, 8, 1)),

The handler function is going to return a Python data structure, and we’ll add decorator functions that can convert this data structure to JSON and HTML:

import json
from cgi import escape
from functools import wraps

def to_json(func):
    Wrap a Pesto handler to return a JSON-encoded string from a python
    data structure.

    def to_json(request, *args, **kwargs):
        result = func(request, *args, **kwargs)
        if isinstance(result, Response):
            return result
        return Response(
    return to_json

def to_html(func):
    def to_html(request, *args, **kwargs):

        data = func(request, *args, **kwargs)
        if not data:
                return Response([], content_type='text/html')

        keys = sorted(data[0].keys())
        result = ['<table>\n']
        result.extend('  <th>%s</th>\n' % escape(key) for key in keys)
        for item in data:
                result.extend('  <td>%s</td>\n' % escape(str(item[key])) for key in keys)
        return Response(result)
    return to_html

(Note that for a real world application you should use a templating system rather than putting HTML directly in your code. But for this small example it’s fine).

Now we can write a handler function to serve the data. DispatcherApp.match has a decorators argument that allows us to use the same function to serve both the HTML and JSON versions by wrapping it in different decorators for each:

from pesto import DispatcherApp
app = DispatcherApp()
@app.match('/orders.json', 'GET', decorators=[to_json])
@app.match('/orders.html', 'GET', decorators=[to_html])
def list_orders(request):
    return [
                    'date': order.date.strftime('%Y-%m-%d'),
                    'price': order.price,
            } for order in orders

We can now call this function in three ways. First, the HTML version:

>>> from pesto.testing import TestApp
>>> print TestApp(app).get('/orders.html').body

And the JSON version:

>>> print TestApp(app).get('/orders.json').body
[{"date": "2009-07-01", "price": 12.99}, {"date": "2009-08-01", "price": 7.75}, {"date": "2009-08-01", "price": 8.25}]

Finally, we can call the function just as a regular python function. We need to pass the function a (dummy) request object in this case:

>>> from pprint import pprint
>>> from pesto.testing import make_environ
>>> dummy_request = make_environ()
>>> pprint(list_orders(dummy_request))
[{'date': '2009-07-01', 'price': 12.99},
 {'date': '2009-08-01', 'price': 7.75},
 {'date': '2009-08-01', 'price': 8.25}]

pesto.dispatch API documentation


URL dispatcher WSGI application to map incoming requests to handler functions.

Example usage:

>>> from pesto.dispatch import DispatcherApp
>>> dispatcher = DispatcherApp()
>>> @dispatcher.match('/page/<id:int>', 'GET')
... def page(request, id):
...     return Response(['You requested page %d' % id])
>>> from pesto.testing import TestApp
>>> TestApp(dispatcher).get('/page/42').body
'You requested page 42'
class pesto.dispatch.DispatcherApp(prefix='', cache_size=0, debug=False)

Match URLs to pesto handlers.

Use the match, imatch and matchre methods to associate URL patterns and HTTP methods to callables:

>>> import pesto.dispatch
>>> from pesto.response import Response
>>> dispatcher = pesto.dispatch.DispatcherApp()
>>> def search_form(request):
...     return Response(['Search form page'])
>>> def do_search(request):
...     return Response(['Search page'])
>>> def faq(request):
...     return Response(['FAQ page'])
>>> def faq_category(request):
...     return Response(['FAQ category listing'])
>>> dispatcher.match("/search", GET=search_form, POST=do_search)
>>> dispatcher.match("/faq", GET=faq)
>>> dispatcher.match("/faq/<category:unicode>", GET=faq_category)

The last matching pattern wins.

Patterns can also be named so that they can be retrieved using the urlfor method:

>>> from pesto.testing import TestApp
>>> from pesto.request import Request
>>> # URL generation methods require an request object
>>> request = Request(TestApp.make_environ())
>>> dispatcher = pesto.dispatch.DispatcherApp()
>>> dispatcher.matchpattern(
...     ExtensiblePattern("/faq/<category:unicode>"), 'faq_category', None, None, GET=faq_category
... )
>>> dispatcher.urlfor('faq_category', request, category='foo')

Decorated handler functions also grow a url method that generates valid URLs for the function:

>>> from pesto.testing import TestApp
>>> request = Request(TestApp.make_environ())
>>> @dispatcher.match("/faq/<category:unicode>", "GET")
... def faq_category(request, category):
...     return ['content goes here']
>>> faq_category.url(category='alligator')

Create a new DispatcherApp.

  • prefix – A prefix path that will be prepended to all functions mapped via DispatcherApp.match
  • cache_size – if non-zero, a least recently used (lru) cache of this size will be maintained, mapping URLs to callables.

Add the patterns from dispatcher other to this dispatcher.


>>> from pesto.testing import TestApp
>>> d1 = dispatcher_app()
>>> d1.match('/foo', GET=lambda request: Response(['d1:foo']))
>>> d2 = dispatcher_app()
>>> d2.match('/bar', GET=lambda request: Response(['d2:bar']))
>>> combined = dispatcher_app().combine(d1, d2)
>>> TestApp(combined).get('/foo').body
>>> TestApp(combined).get('/bar').body

Note settings other than patterns are not carried over from the other dispatchers - if you intend to use the debug flag or caching options, you must explicitly set them in the combined dispatcher:

>>> combined = dispatcher_app(debug=True, cache_size=50).combine(d1, d2)
>>> TestApp(combined).get('/foo').body

alias of ExtensiblePattern

gettarget(path, method, request)

Generate dispatch targets methods matching the request URI.

For each function matched, yield a tuple of:

(function, predicate, positional_args, keyword_args)

Positional and keyword arguments are parsed from the URI


>>> from pesto.testing import TestApp
>>> d = DispatcherApp()

>>> def show_entry(request):
...     return [ "Show entry page" ]
>>> def new_entry_form(request):
...     return [ "New entry form" ]

>>> d.match(r'/entries/new',          GET=new_entry_form)
>>> d.match(r'/entries/<id:unicode>', GET=show_entry)

>>> request = Request(TestApp.make_environ(PATH_INFO='/entries/foo'))
>>> list(d.gettarget(u'/entries/foo', 'GET', request))  
[(<function show_entry ...>, None, (), {'id': u'foo'})]

>>> request = Request(TestApp.make_environ(PATH_INFO='/entries/new'))
>>> list(d.gettarget(u'/entries/new', 'GET', request)) 
[(<function new_entry_form ...>, None, (), {}), (<function show_entry ...>, None, (), {'id': u'new'})]
match(pattern, *args, **dispatchers)

Function decorator to match the given URL to the decorated function, using the default pattern type.

A name that can be later used to retrieve the url with urlfor (keyword-only argument)
A callable that is used to decide whether to match this pattern. The callable must take a Request object as its only parameter and return True or False. (keyword-only argument)

A list of function decorators that will be applied to the function when called as a WSGI application. (keyword-only argument).

The purpose of this is to allow functions to behave differently when called as an API function or as a WSGI application via a dispatcher.

matchpattern(pattern, name, predicate, decorators, *args, **methods)

Match a URL with the given pattern, specified as an instance of Pattern.

A pattern object, eg ExtensiblePattern('/pages/<name:unicode>')
A name that can be later used to retrieve the url with urlfor, or None
A callable that is used to decide whether to match this pattern, or None. The callable must take a Request object as its only parameter and return True or False.


>>> from pesto.response import Response
>>> dispatcher = DispatcherApp()
>>> def view_items(request, tag):
...     return Response(["yadda yadda yadda"])
>>> dispatcher.matchpattern(
...     ExtensiblePattern(
...          "/items-by-tag/<tag:unicode>",
...     ),
...     'view_items',
...     None,
...     None,
...     GET=view_items
... )

URLs can later be generated with the urlfor method on the dispatcher object:

>>> Response.redirect(dispatcher.urlfor(
...     'view_items',
...     tag='spaghetti',
... ))                                      
<pesto.response.Response object at ...>

Or, if used in the second style as a function decorator, by calling the function’s .url method:

>>> @dispatcher.match('/items-by-tag/<tag:unicode>', 'GET')
... def view_items(request, tag):
...     return Response(["yadda yadda yadda"])
>>> Response.redirect(view_items.url(tag='spaghetti')) 
<pesto.response.Response object at ...>

Note that the url function can take optional query and fragment paraments to help in URL construction:

>>> from pesto.testing import TestApp
>>> from pesto.dispatch import DispatcherApp
>>> from pesto.request import Request
>>> dispatcher = DispatcherApp()
>>> request = Request(TestApp.make_environ())
>>> @dispatcher.match('/pasta', 'GET')
... def pasta(request):
...     return Response(["Tasty spaghetti!"])
>>> pasta.url(request, query={'sauce' : 'ragu'}, fragment='eat')

Return a list of acceptable HTTP methods for URI path path.


Return a 404 Not Found response.

Called when the dispatcher cannot find a matching URI.

status405_application(request, valid_methods)

Return a 405 Method Not Allowed response.

Called when the dispatcher can find a matching URI, but the HTTP methods do not match.

urlfor(dispatcher_name, request=None, *args, **kwargs)

Return the URL corresponding to the dispatcher named with dispatcher_name.


alias of DispatcherApp

exception pesto.dispatch.NamedURLNotFound

Raised if the named url can’t be found (eg in urlfor).

exception pesto.dispatch.URLGenerationError

Error generating the requested URL

Table Of Contents

Previous topic

The response object

Next topic


This Page