When a Drakken app receives a request for a web page, the request is routed to the appropriate route handler, also called a view or page controller. Handlers can be either functions or classes.

Handler function

The demo app already has one route handler function: home(). Let’s add another:

def about(request, response):
    response.text = 'We love Python'

Launch and visit You should see the message We love Python.

Handler class

Handler classes are a bit more complicated than handler functions but very useful for creating a RESTful API. The BooksResource class handles GET and POST requests to the /book/ route:

class BooksResource:
    def get(self, request, response):
        response.text = 'Books page'

    def post(self, request, response):
        response.text = 'Endpoint to create a book'

Launch and visit You should see the message Books page.

Multiple routes

A single handler can be used for multiple routes by stacking the route decorators. Add the /my-home-page/ and /home/ route decorators to the home() route handler:

def home(request, response):
    response.text = 'Hello from the HOME page'

Launch and visit and You should see the home page.

URL parameters

Route handlers can process URL parameters. Add the following route handlers to the demo app.

def greeting(request, response, name):
    response.text = f'Hello, {name}'

def tell(request, response, age):
    response.text = f'Your age is {age}'

Launch and visit You should see the message Hello, beautiful. Visit You should see the message Your age is 42.

URL parameters can be matched by data type using the parse module. The function tell() uses the digit data type. For a list of data types see the format specification.

The trailing slash question

Some sites use a trailing slash on their URLs:

Some don’t:

Does it matter? Not really but you should be consistent. Search engines see /blog/kittens/ and /blog/kittens as two different URLs so your page’s search engine ranking gets cut in half.

Google says you should use a 301 redirect from the duplicate to the preferred version (To slash or not to slash, Google Search Central Blog, April 21, 2010). Following their advice, Drakken can redirect visitors who forget a trailing slash or add one by accident. Just set TRAILING_SLASH_REDIRECT: True in your config file.