sanic/docs/routing.md

45 lines
1.5 KiB
Markdown
Raw Normal View History

2016-10-14 12:51:08 +01:00
# Routing
Sanic comes with a basic router that supports request parameters. To specify a parameter, surround it with carrots like so: `<PARAM>`. Request parameters will be passed to the request handler functions as keyword arguments. To specify a type, add a :type after the parameter name, in the carrots. If the parameter does not match the type supplied, Sanic will throw a NotFound exception, resulting in a 404 page not found error.
2016-10-14 12:51:08 +01:00
## Examples
```python
from sanic import Sanic
2016-10-14 12:58:09 +01:00
from sanic.response import text
2016-10-14 12:51:08 +01:00
@app.route('/tag/<tag>')
async def tag_handler(request, tag):
2016-10-14 12:51:08 +01:00
return text('Tag - {}'.format(tag))
@app.route('/number/<integer_arg:int>')
async def integer_handler(request, integer_arg):
2016-10-14 12:51:08 +01:00
return text('Integer - {}'.format(integer_arg))
@app.route('/number/<number_arg:number>')
async def number_handler(request, number_arg):
2016-10-18 13:13:37 +01:00
return text('Number - {}'.format(number_arg))
2016-10-14 12:51:08 +01:00
@app.route('/person/<name:[A-z]>')
async def person_handler(request, name):
return text('Person - {}'.format(name))
2016-10-14 12:51:08 +01:00
@app.route('/folder/<folder_id:[A-z0-9]{0,4}>')
2016-10-14 12:51:08 +01:00
async def folder_handler(request, folder_id):
return text('Folder - {}'.format(folder_id))
async def handler1(request):
return text('OK')
app.add_route(handler1, '/test')
async def handler(request, name):
return text('Folder - {}'.format(name))
app.add_route(handler, '/folder/<name>')
async def person_handler(request, name):
return text('Person - {}'.format(name))
app.add_route(handler, '/person/<name:[A-z]>')
```