Refs #33562 -- Made HttpResponse.set_cookie() raise ValueError when both "expires" and "max_age" are passed.

This fixes the case where you might pass set_cookie(expires=val, max_age=val)
and max_age is silently ignored.
This commit is contained in:
Luke Plant 2022-03-04 13:05:07 +00:00 committed by Mariusz Felisiak
parent ae2da5ba65
commit f3bf6c4218
2 changed files with 10 additions and 0 deletions

View File

@ -244,6 +244,8 @@ class HttpResponseBase:
delta = delta + datetime.timedelta(seconds=1) delta = delta + datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires. # Just set max_age - the max_age logic will set expires.
expires = None expires = None
if max_age is not None:
raise ValueError("'expires' and 'max_age' can't be used together.")
max_age = max(0, delta.days * 86400 + delta.seconds) max_age = max(0, delta.days * 86400 + delta.seconds)
else: else:
self.cookies[key]["expires"] = expires self.cookies[key]["expires"] = expires

View File

@ -76,6 +76,14 @@ class SetCookieTests(SimpleTestCase):
response.set_cookie("max_age", max_age=timedelta(hours=1)) response.set_cookie("max_age", max_age=timedelta(hours=1))
self.assertEqual(response.cookies["max_age"]["max-age"], 3600) self.assertEqual(response.cookies["max_age"]["max-age"], 3600)
def test_max_age_with_expires(self):
response = HttpResponse()
msg = "'expires' and 'max_age' can't be used together."
with self.assertRaisesMessage(ValueError, msg):
response.set_cookie(
"max_age", expires=datetime(2000, 1, 1), max_age=timedelta(hours=1)
)
def test_httponly_cookie(self): def test_httponly_cookie(self):
response = HttpResponse() response = HttpResponse()
response.set_cookie("example", httponly=True) response.set_cookie("example", httponly=True)