From 17472c3304050fbbf7a65976ab7b392184d081d1 Mon Sep 17 00:00:00 2001 From: SirAbhi13 Date: Thu, 24 Nov 2022 17:05:59 +0530 Subject: [PATCH] Fixed #34173 -- Skipped saving sessions on 5xx responses. --- django/contrib/sessions/middleware.py | 4 ++-- tests/sessions_tests/tests.py | 15 ++++++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/django/contrib/sessions/middleware.py b/django/contrib/sessions/middleware.py index 2fcd7d508a..9c934f9ddd 100644 --- a/django/contrib/sessions/middleware.py +++ b/django/contrib/sessions/middleware.py @@ -53,8 +53,8 @@ class SessionMiddleware(MiddlewareMixin): expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. - # Skip session save for 500 responses, refs #3881. - if response.status_code != 500: + # Skip session save for 5xx responses. + if response.status_code < 500: try: request.session.save() except UpdateError: diff --git a/tests/sessions_tests/tests.py b/tests/sessions_tests/tests.py index 96f8dbcd5b..d13c485342 100644 --- a/tests/sessions_tests/tests.py +++ b/tests/sessions_tests/tests.py @@ -715,7 +715,7 @@ class SessionMiddlewareTests(TestCase): ) def test_session_save_on_500(self): - def response_500(requset): + def response_500(request): response = HttpResponse("Horrible error") response.status_code = 500 request.session["hello"] = "world" @@ -727,6 +727,19 @@ class SessionMiddlewareTests(TestCase): # The value wasn't saved above. self.assertNotIn("hello", request.session.load()) + def test_session_save_on_5xx(self): + def response_503(request): + response = HttpResponse("Service Unavailable") + response.status_code = 503 + request.session["hello"] = "world" + return response + + request = self.request_factory.get("/") + SessionMiddleware(response_503)(request) + + # The value wasn't saved above. + self.assertNotIn("hello", request.session.load()) + def test_session_update_error_redirect(self): def response_delete_session(request): request.session = DatabaseSession()