add doc for middleware functions mounted on a specific handler in route decorator

This commit is contained in:
PandaFeeder 2017-05-13 23:19:10 +08:00
parent c6d9f3683d
commit 03700049b6

View File

@ -26,6 +26,32 @@ async def print_on_response(request, response):
print("I print when a response is returned by the server") print("I print when a response is returned by the server")
``` ```
Besides above two types of middleware declared using the `@app.middleware` decorator,
you can aslo mount middleware functions to a specific handler as `'request'` or `'response'`
middleware. Request middleware receives exactly the same parameters as your handler function.
Response middleware receives an additional `'response'` parameter comparing to Request middleware.
```python
async def authenticate(request, lock_id):
if lock_id != request.headers['key_id']:
return response.json(
status=403,
headers={"Authentication": "Failed"}
)
async def say_goodby(request, respone, lock_id):
respone.headers.update({"Add-Header": "May the force be with you"})
@app.route('/lock/<lock_id>', middleware={"request": authenticate, "response": say_goodbye})
async def handler(request, lock_id):
return response.json({"message": "welcome back"})
```
In above example, you can also pass in multi Request or Response middlewares
as a list of functions to the middleware keyword argument in route decorator.
They will be excuted in order if no early response happens. Please see below
`'Responding early'` section for detail.
## Modifying the request or response ## Modifying the request or response
Middleware can modify the request or response parameter it is given, *as long Middleware can modify the request or response parameter it is given, *as long
@ -69,6 +95,9 @@ async def halt_response(request, response):
return text('I halted the response') return text('I halted the response')
``` ```
Above description also works for middleware functions that mounted on a specific handler
using the route decorate.
## Listeners ## Listeners
If you want to execute startup/teardown code as your server starts or closes, you can use the following listeners: If you want to execute startup/teardown code as your server starts or closes, you can use the following listeners: