-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
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
simplifying middleware #2252
Merged
Merged
simplifying middleware #2252
Changes from 8 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
376c31c
simplifying middleware, fix #2225
samuelcolvin d5bc052
set depeciation message
samuelcolvin 7dfb2f7
Update test_web_middleware.py
asvetlov 5b7fdba
allow mixed middleware styles
samuelcolvin 4952e10
Merge branch 'master' into new-middleware
asvetlov cc3287a
use decorator for new middleware
samuelcolvin 8dc0701
Merge branch 'master' into new-middleware
asvetlov f6396fe
rename decorator to 'middleware' and add docs
samuelcolvin 9f12f8f
Merge branch 'master' into new-middleware
asvetlov e08ca47
tweaking docs
samuelcolvin 11e857d
fix spelling
samuelcolvin c7df4b4
'streamed response' not 'steamed response' :-)
samuelcolvin File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
Simplify middleware | ||
|
||
So they are simple coroutines rather than coroutine factories | ||
returning coroutines. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -997,42 +997,31 @@ the keyword-only ``middlewares`` parameter when creating an | |
app = web.Application(middlewares=[middleware_factory_1, | ||
middleware_factory_2]) | ||
|
||
A *middleware factory* is simply a coroutine that implements the logic of a | ||
*middleware*. For example, here's a trivial *middleware factory*:: | ||
A *middleware* is just a coroutine that can modify either the request or | ||
response. For example, here's a simple *middleware* which appends | ||
``' wink'`` to the response:: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The example doesn't work with streamed responses and websockets. Maybe we should mention it (in brackets). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done. |
||
|
||
async def middleware_factory(app, handler): | ||
async def middleware_handler(request): | ||
return await handler(request) | ||
return middleware_handler | ||
|
||
Every *middleware factory* should accept two parameters, an | ||
:class:`app <Application>` instance and a *handler*, and return a new handler. | ||
from aiohttp.web import middleware | ||
|
||
The *handler* passed in to a *middleware factory* is the handler returned by | ||
the **next** *middleware factory*. The last *middleware factory* always receives | ||
the :ref:`request handler <aiohttp-web-handler>` selected by the router itself | ||
(by :meth:`UrlDispatcher.resolve`). | ||
@middleware | ||
async def middleware(request, handler): | ||
resp = await handler(request) | ||
resp.text = resp.text + ' wink' | ||
return resp | ||
|
||
.. note:: | ||
|
||
Both the outer *middleware_factory* coroutine and the inner | ||
*middleware_handler* coroutine are called for every request handled. | ||
|
||
*Middleware factories* should return a new handler that has the same signature | ||
as a :ref:`request handler <aiohttp-web-handler>`. That is, it should accept a | ||
single :class:`Request` instance and return a :class:`Response`, or raise an | ||
exception. | ||
Every *middleware* should accept two parameters, a | ||
:class:`request <Request>` instance and a *handler*, and return the response. | ||
|
||
Internally, a single :ref:`request handler <aiohttp-web-handler>` is constructed | ||
by applying the middleware chain to the original handler in reverse order, | ||
and is called by the :class:`RequestHandler` as a regular *handler*. | ||
|
||
Since *middleware factories* are themselves coroutines, they may perform extra | ||
Since *middlewares* are themselves coroutines, they may perform extra | ||
``await`` calls when creating a new handler, e.g. call database etc. | ||
|
||
*Middlewares* usually call the inner handler, but they may choose to ignore it, | ||
*Middlewares* usually call the handler, but they may choose to ignore it, | ||
e.g. displaying *403 Forbidden page* or raising :exc:`HTTPForbidden` exception | ||
if user has no permissions to access the underlying resource. | ||
if the user doesn't have permissions to access the underlying resource. | ||
They may also render errors raised by the handler, perform some pre- or | ||
post-processing like handling *CORS* and so on. | ||
|
||
|
@@ -1043,23 +1032,19 @@ The following code demonstrates middlewares execution order:: | |
print('Handler function called') | ||
return web.Response(text="Hello") | ||
|
||
async def middleware1(app, handler): | ||
async def middleware_handler(request): | ||
print('Middleware 1 called') | ||
response = await handler(request) | ||
print('Middleware 1 finished') | ||
|
||
return response | ||
return middleware_handler | ||
@web.middleware | ||
async def middleware1(request, handler): | ||
print('Middleware 1 called') | ||
response = await handler(request) | ||
print('Middleware 1 finished') | ||
return response | ||
|
||
@web.middleware | ||
async def middleware2(app, handler): | ||
async def middleware_handler(request): | ||
print('Middleware 2 called') | ||
response = await handler(request) | ||
print('Middleware 2 finished') | ||
|
||
return response | ||
return middleware_handler | ||
print('Middleware 2 called') | ||
response = await handler(request) | ||
print('Middleware 2 finished') | ||
return response | ||
|
||
|
||
app = web.Application(middlewares=[middleware1, middleware2]) | ||
|
@@ -1089,20 +1074,62 @@ a JSON REST service:: | |
body=json.dumps({'error': message}).encode('utf-8'), | ||
content_type='application/json') | ||
|
||
@web.middleware | ||
async def error_middleware(app, handler): | ||
try: | ||
response = await handler(request) | ||
if response.status == 404: | ||
return json_error(response.message) | ||
return response | ||
except web.HTTPException as ex: | ||
if ex.status == 404: | ||
return json_error(ex.reason) | ||
raise | ||
|
||
app = web.Application(middlewares=[error_middleware]) | ||
|
||
|
||
Old Style Middleware | ||
.................... | ||
|
||
.. deprecated:: 2.3 | ||
|
||
Prior to *v2.3* middleware required an outer *middleware factory* | ||
which returned the middleware coroutine. Since *v2.3* this is not | ||
required; instead the ``@middleware`` decorator should | ||
be used. | ||
|
||
However, old style middleware (with an outer factory and no ``@middleware`` | ||
decorator) is still supported. Furthermore, old and new style middleware | ||
can be mixed. | ||
|
||
A *middleware factory* is simply a coroutine that implements the logic of a | ||
*middleware*. For example, here's a trivial *middleware factory*:: | ||
|
||
async def middleware_factory(app, handler): | ||
async def middleware_handler(request): | ||
try: | ||
response = await handler(request) | ||
if response.status == 404: | ||
return json_error(response.message) | ||
return response | ||
except web.HTTPException as ex: | ||
if ex.status == 404: | ||
return json_error(ex.reason) | ||
raise | ||
resp = await handler(request) | ||
resp.text = resp.text + ' wink' | ||
return resp | ||
return middleware_handler | ||
|
||
app = web.Application(middlewares=[error_middleware]) | ||
Every *middleware factory* should accept two parameters, an | ||
:class:`app <Application>` instance and a *handler*, and return a new handler. | ||
|
||
The *handler* passed in to a *middleware factory* is the handler returned by | ||
the **next** *middleware factory*. The last *middleware factory* always receives | ||
the :ref:`request handler <aiohttp-web-handler>` selected by the router itself | ||
(by :meth:`UrlDispatcher.resolve`). | ||
|
||
.. note:: | ||
|
||
Both the outer *middleware_factory* coroutine and the inner | ||
*middleware_handler* coroutine are called for every request handled. | ||
|
||
*Middleware factories* should return a new handler that has the same signature | ||
as a :ref:`request handler <aiohttp-web-handler>`. That is, it should accept a | ||
single :class:`Request` instance and return a :class:`Response`, or raise an | ||
exception. | ||
|
||
.. _aiohttp-web-signals: | ||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment is irrelevant