2018-08-28 13:58:03 +00:00
|
|
|
|
|
|
|
Starlette includes a `Router` class which is an ASGI application that
|
2018-10-29 09:22:45 +00:00
|
|
|
dispatches incoming requests to endpoints or submounted applications.
|
2018-08-28 13:58:03 +00:00
|
|
|
|
|
|
|
```python
|
2018-10-29 09:22:45 +00:00
|
|
|
from starlette.routing import Mount, Route, Router
|
2018-08-28 13:58:03 +00:00
|
|
|
from myproject import Homepage, SubMountedApp
|
|
|
|
|
|
|
|
|
|
|
|
app = Router([
|
2018-10-29 09:22:45 +00:00
|
|
|
Route('/', endpoint=Homepage, methods=['GET']),
|
|
|
|
Mount('/mount', app=SubMountedApp)
|
2018-08-28 13:58:03 +00:00
|
|
|
])
|
|
|
|
```
|
|
|
|
|
|
|
|
Paths can use URI templating style to capture path components.
|
|
|
|
|
|
|
|
```python
|
2018-10-29 09:22:45 +00:00
|
|
|
Route('/users/{username}', endpoint=User, methods=['GET'])
|
2018-08-28 13:58:03 +00:00
|
|
|
```
|
|
|
|
|
2018-10-29 09:22:45 +00:00
|
|
|
Path parameters are made available in the request, as the `request.path_params`
|
|
|
|
dictionary.
|
2018-08-28 13:58:03 +00:00
|
|
|
|
2018-10-29 09:22:45 +00:00
|
|
|
Because the target of a `Mount` is an ASGI instance itself, routers
|
2018-08-28 13:58:03 +00:00
|
|
|
allow for easy composition. For example:
|
|
|
|
|
|
|
|
```python
|
|
|
|
app = Router([
|
2018-10-29 09:22:45 +00:00
|
|
|
Route('/', endpoint=Homepage, methods=['GET']),
|
|
|
|
Mount('/users', app=Router([
|
|
|
|
Route('/', endpoint=Users, methods=['GET', 'POST']),
|
|
|
|
Route('/{username}', endpoint=User, methods=['GET']),
|
2018-08-28 13:58:03 +00:00
|
|
|
]))
|
|
|
|
])
|
|
|
|
```
|
|
|
|
|
2018-08-30 13:42:39 +00:00
|
|
|
The router will respond with "404 Not found" or "405 Method not allowed"
|
2018-08-28 13:58:03 +00:00
|
|
|
responses for requests which do not match.
|