Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document middleware on_request and on_response #2398

Merged
merged 4 commits into from
Feb 13, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions sanic/mixins/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ def middleware(
self, middleware_or_request, attach_to="request", apply=True
):
"""
Decorate and register middleware to be called before a request.
Can either be called as *@app.middleware* or
*@app.middleware('request')*
Decorate and register middleware to be called before a request
is handled or after a response is created. Can either be called as
*@app.middleware* or *@app.middleware('request')*.

`See user guide re: middleware
<https://sanicframework.org/guide/basics/middleware.html>`__
Expand Down Expand Up @@ -47,12 +47,25 @@ def register_middleware(middleware, attach_to="request"):
)

def on_request(self, middleware=None):
"""Register a middleware to be called before a request is handled.

This is the same as *@app.middleware('request')*.

:param: middleware: A callable that takes in request.
"""
if callable(middleware):
return self.middleware(middleware, "request")
else:
return partial(self.middleware, attach_to="request")

def on_response(self, middleware=None):
"""Register a middleware to be called after a response is created.

This is the same as *@app.middleware('response')*.

:param: middleware:
A callable that takes in a request and its response.
"""
if callable(middleware):
return self.middleware(middleware, "response")
else:
Expand Down