From d0453ed56820e32802be743bf7a7b7027f9c9589 Mon Sep 17 00:00:00 2001 From: Sam Bull Date: Sat, 14 Nov 2020 15:24:43 +0000 Subject: [PATCH 1/7] Backport fix for setting cookies --- CHANGES/5233.bugfix | 1 + aiohttp/web_protocol.py | 21 ++++++++++----------- tests/test_web_exceptions.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 11 deletions(-) --- /dev/null +++ b/CHANGES/5233.bugfix @@ -0,0 +1 @@ +Fix cookies disappearing from HTTPExceptions. --- a/aiohttp/web_protocol.py +++ b/aiohttp/web_protocol.py @@ -423,9 +423,7 @@ class RequestHandler(BaseProtocol): finally: self._current_request = None except HTTPException as exc: - resp = Response( - status=exc.status, reason=exc.reason, text=exc.text, headers=exc.headers - ) + resp = exc reset = await self.finish_response(request, resp, start_time) except asyncio.CancelledError: raise @@ -437,6 +435,15 @@ class RequestHandler(BaseProtocol): resp = self.handle_error(request, 500, exc) reset = await self.finish_response(request, resp, start_time) else: + # Deprecation warning (See #2415) + if getattr(resp, "__http_exception__", False): + warnings.warn( + "returning HTTPException object is deprecated " + "(#2415) and will be removed, " + "please raise the exception instead", + DeprecationWarning, + ) + reset = await self.finish_response(request, resp, start_time) return resp, reset @@ -486,14 +493,6 @@ class RequestHandler(BaseProtocol): except (asyncio.CancelledError, ConnectionError): self.log_debug("Ignored premature client disconnection") break - # Deprecation warning (See #2415) - if getattr(resp, "__http_exception__", False): - warnings.warn( - "returning HTTPException object is deprecated " - "(#2415) and will be removed, " - "please raise the exception instead", - DeprecationWarning, - ) # Drop the processed task from asyncio.Task.all_tasks() early del task --- a/tests/test_web_exceptions.py +++ b/tests/test_web_exceptions.py @@ -203,3 +203,31 @@ def test_HTTPException_retains_cause() - tb = "".join(format_exception(ei.type, ei.value, ei.tb)) assert "CustomException" in tb assert "direct cause" in tb + + +async def test_HTTPException_retains_cookie(aiohttp_client): + @web.middleware + async def middleware(request, handler): + try: + return await handler(request) + except web.HTTPException as exc: + exc.set_cookie("foo", request["foo"]) + raise exc + + async def save(request): + request["foo"] = "works" + raise web.HTTPFound("/show") + + async def show(request): + return web.Response(text=request.cookies["foo"]) + + app = web.Application(middlewares=[middleware]) + app.router.add_route("GET", "/save", save) + app.router.add_route("GET", "/show", show) + client = await aiohttp_client(app) + + resp = await client.get("/save") + assert resp.status == 200 + assert str(resp.url)[-5:] == "/show" + text = await resp.text() + assert text == "works"