Source

wheezy.routing / doc / examples.rst

Examples

We start with a simple helloworld example, than add a bit more modularity in server time. Before we proceed with examples below let setup virtualenv environment:

$ virtualenv env
$ env/bin/easy_install wheezy.routing

Hello World

helloworld.py shows you how to use :ref:`wheezy.routing` in pretty a simple WSGI application:

Let have a look through each line in this application. First of all we import :py:class:`~wheezy.routing.PathRouter` that is actually just an exporting name for :py:class:`~wheezy.routing.router.PathRouter`:

Next we create a pretty simple WSGI handler to provide a response.

In addition let add a handler for not found response.

The declaration and mapping of pattern to handler following. We create an instance of PathRouter class and pass mapping that in this partucular case is a tuple of two values: pattern and handler.

The first pattern '/' will match only root path of the request (it is finishing route in match chain). The second pattern '/{any}' is a curly expression that is translated to regular expression that ultimately match any path and is finishing route as well.

main function serves as WSGI application entry point. The only thing we do here is to get a value of WSGI environment variable PATH_INFO (the remainder of the request URL's path) and pass to router :py:meth:`~wheezy.routing.router.PathRouter.match` method, in return we get handler and kwargs (parameters discovered from matching rule, that we ignore for now).

The rest in the helloworld application launch a simple wsgi server. Try it by running:

$ python helloworld.py

Visit http://localhost:8080/.

Server Time

Server time application consists of two screens. The first one has a link to the second that shows the time on server. The second page will be mapped as a separate application with its own routing. The design used in this sample is modular. Let's start with config module. The only thing we need here is an instance of PathRouter.

view module is pretty straight: a welcome view with a link to server_time view. The server time page returns server time. And finally catch all not_found handler to display http 404 error, page not found.

So what is interesting in welcome view is a way how we get an url for server_time view.

The name now was used during url mapping that you can see below (module urls):

server_urls than included under the parent path server/, so anything that starts from server/ path will be directed to server_urls url mapping. Lastly we add a curly expression that maps any url match to our not_found handler.

We combine that all together in app module.

Try it by running:

$ python app.py

Visit http://localhost:8080/.