Skip to content

Commit

Permalink
Preserve view handler function attributes across middlewares
Browse files Browse the repository at this point in the history
  • Loading branch information
Gustavo Carneiro committed Oct 16, 2019
1 parent 6236536 commit 391c592
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES/4174.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Preserve view handler function attributes across middlewares
6 changes: 4 additions & 2 deletions aiohttp/web_app.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
import logging
import warnings
from functools import partial
from functools import partial, update_wrapper
from typing import ( # noqa
TYPE_CHECKING,
Any,
Expand Down Expand Up @@ -325,7 +325,9 @@ async def _handle(self, request: Request) -> StreamResponse:
for app in match_info.apps[::-1]:
assert app.pre_frozen, "middleware handlers are not ready"
for m in app._middlewares_handlers: # noqa
handler = partial(m, handler=handler)
handler = update_wrapper(
partial(m, handler=handler), handler
)

resp = await handler(request)

Expand Down
21 changes: 21 additions & 0 deletions tests/test_web_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,18 @@ async def test_middleware_chain(loop, aiohttp_client) -> None:
async def handler(request):
return web.Response(text='OK')

handler.annotation = "annotation_value"

async def handler2(request):
return web.Response(text='OK')

middleware_annotation_seen_values = []

def make_middleware(num):
async def middleware(request, handler):
middleware_annotation_seen_values.append(
getattr(handler, "annotation", None)
)
resp = await handler(request)
resp.text = resp.text + '[{}]'.format(num)
return resp
Expand All @@ -60,11 +70,22 @@ async def middleware(request, handler):
app.middlewares.append(make_middleware(1))
app.middlewares.append(make_middleware(2))
app.router.add_route('GET', '/', handler)
app.router.add_route('GET', '/r2', handler2)
client = await aiohttp_client(app)
resp = await client.get('/')
assert 200 == resp.status
txt = await resp.text()
assert 'OK[2][1]' == txt
assert middleware_annotation_seen_values == [
'annotation_value', 'annotation_value'
]

# check that attributes from handler are not applied to handler2
resp = await client.get('/r2')
assert 200 == resp.status
assert middleware_annotation_seen_values == [
'annotation_value', 'annotation_value', None, None
]


@pytest.fixture
Expand Down

0 comments on commit 391c592

Please sign in to comment.