3. Application routes

This is the point where we want to define our routes that will be used to map view callables to request paths.

URL dispatch provides a simple way to map URLs to view code using a simple pattern matching language.

Our application will consist of a few sections:

  • index page that will list all of our sorted blog entries
  • a sign in/sign out section that will be used for authentication
  • a way to create and edit our blog posts

Our URLs will look like the following.

To sign in users:


When a user visits http://somedomain.foo/sign/in, the view callable responsible for signing in the user based on POST variables from the request will be executed.

To sign out users:


The index page (this was already defined via the alchemy scaffold we used earlier, under the name “home”):


Create new, or edit existing blog entries:


You probably noticed that this URL appears unusual. The {action} part in the matching pattern determines that this part is dynamic, so our URL could look like any of the following:


This single route could map to different views.

Finally a route used to view our blog entries:


This route constists of two dynamic parts, {id:\d+} and {slug}.

The :\d+ pattern means that the route will only match digits. So an URL where the first dynamic part consists of only digits like the following would be matched:


But the below example would not be matched, because the first dynamic part contains a non-digit character:


Adding routes to the application configuration

Let’s add our routes to the configurator immediately after the home route in our routes.py at the root of our project.

def includeme(config):
    config.add_static_view('static', 'static', cache_max_age=3600)
    config.add_route('home', '/')
    config.add_route('blog', '/blog/{id:\d+}/{slug}')
    config.add_route('blog_action', '/blog/{action}')
    config.add_route('auth', '/sign/{action}')

Now we are ready to develop views.

Next: 4. Initial views.