Examples

We start with a simple helloworld example, than add a bit more modularity in server time.

Hello World

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

from wheezy.routing import Router


def hello_world(environ, start_response):
    start_response('200 OK', [
        ('Content-type', 'text/html')
    ])
    return ["Hello World!".encode('utf8')]


r = Router()
r.add_routes([
    ('/', hello_world)
])


def main(environ, start_response):
    handler, kwargs = r.match(environ['PATH_INFO'])
    return handler(environ, start_response)

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    try:
        print('Visit http://localhost:8080/')
        make_server('', 8080, main).serve_forever()
    except KeyboardInterrupt:
        pass
    print('\nThanks!')

Let have a look through each line in this application. First of all we import Router that is actually just an exporting name for PathRouter:

from wheezy.routing import Router

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

def hello_world(environ, start_response):
    start_response('200 OK', [
        ('Content-type', 'text/html')
    ])
    return ["Hello World!".encode('utf8')]

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

r = Router()
r.add_routes([
    ('/', hello_world)
])

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 match() method, in return we get handler and kwargs (parameters discovered from matching rule, that we ignore for now). Due to specific of the route that ends with / our handler will match any incomming request.

def main(environ, start_response):
    handler, kwargs = r.match(environ['PATH_INFO'])
    return handler(environ, start_response)

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

make run-hello

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 disign used in this sample is moular. Let’s start with config module. The only thing we need here is an instance of Route.

from wheezy.routing import url, Router


router = Router()

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

from datetime import datetime

from config import router as r


def welcome(environ, start_response):
    start_response('200 OK', [
        ('Content-type', 'text/html')
    ])
    return ["Welcome!  <a href='%s'>Server Time</a>" %
            r.path_for('now')]


def server_time(environ, start_response):
    start_response('200 OK', [
        ('Content-type', 'text/plain')
    ])
    return ["The server time is: %s" % datetime.now()]


def not_found(environ, start_response):
    start_response("404 Not Found", [
        ('Content-Type', 'text/plain')
    ])
    return ["Not Found: " + environ['routing.kwargs']['url']]

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

    return ["Welcome!  <a href='%s'>Server Time</a>" %
            r.path_for('now')]

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

from config import url
from views import welcome, server_time, not_found

server_urls = [
    url('time', server_time, name='now')
]

home = [
    ('', welcome),
    ('server/', server_urls)
]

home += [
    url('{url:any}', not_found)
]

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

We combine that all together in app module.

import config
import urls

r = config.router
r.add_routes(urls.home)


def main(environ, start_response):
    handler, kwargs = r.match(environ['PATH_INFO'].lstrip('/'))
    environ['routing.kwargs'] = kwargs
    return map(lambda chunk: chunk.encode('utf8'),
            handler(environ, start_response))

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    try:
        print('Visit http://localhost:8080/')
        make_server('', 8080, main).serve_forever()
    except KeyboardInterrupt:
        pass
    print('\nThanks!')

Try it by running:

make run-time

Visit http://localhost:8080/.

Table Of Contents

Previous topic

Getting Started

Next topic

User Guide

This Page