Routing¶
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:
@app.route('/about-us/')
def about(request, response):
response.text = 'We love Python'
Launch demo.py and visit http://127.0.0.1:8000/about-us/. 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:
@app.route('/book/')
class BooksResource:
def get(self, request, response):
response.text = 'Books page'
def post(self, request, response):
response.text = 'Endpoint to create a book'
Launch demo.py and visit http://127.0.0.1:8000/book/. 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:
@app.route('/my-home-page/')
@app.route('/home/')
@app.route('/')
def home(request, response):
response.text = 'Hello from the HOME page'
Launch demo.py and visit http://127.0.0.1:8000/my-home-page/ and http://127.0.0.1:8000/home/. You should see the home page.
URL parameters¶
Route handlers can process URL parameters. Add the following route handlers to the demo app.
@app.route('/hello/{name}/')
def greeting(request, response, name):
response.text = f'Hello, {name}'
@app.route('/tell/{age:d}')
def tell(request, response, age):
response.text = f'Your age is {age}'
Launch demo.py and visit http://127.0.0.1:8000/hello/beautiful/. You should see the message Hello, beautiful. Visit http://127.0.0.1:8000/tell/42. 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:
foo.com/blog/kittens/
Some don’t:
foo.com/blog/kittens
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.