From 03700049b6ac64c03fc9749f70a7fce96a56c413 Mon Sep 17 00:00:00 2001 From: PandaFeeder Date: Sat, 13 May 2017 23:19:10 +0800 Subject: [PATCH] add doc for middleware functions mounted on a specific handler in route decorator --- docs/sanic/middleware.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/sanic/middleware.md b/docs/sanic/middleware.md index b2e8b45a..b0ca8685 100644 --- a/docs/sanic/middleware.md +++ b/docs/sanic/middleware.md @@ -26,6 +26,32 @@ async def print_on_response(request, response): 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/', 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 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') ``` +Above description also works for middleware functions that mounted on a specific handler +using the route decorate. + ## Listeners If you want to execute startup/teardown code as your server starts or closes, you can use the following listeners: