From 31154c557448cf648212b82c4a1279aa25c7e3f3 Mon Sep 17 00:00:00 2001 From: Youssef Elaasri Date: Sun, 1 Nov 2026 09:54:55 +0100 Subject: [PATCH] Fixed CookieMiddleware.set_cookie() crash with aware expires on Django 5.0+. django.utils.timezone.utc was removed in Django 5.0. --- channels/sessions.py | 2 +- tests/test_http.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/channels/sessions.py b/channels/sessions.py index f1d51d470..bf9ef25d7 100644 --- a/channels/sessions.py +++ b/channels/sessions.py @@ -72,7 +72,7 @@ def set_cookie( if expires is not None: if isinstance(expires, datetime.datetime): if timezone.is_aware(expires): - expires = timezone.make_naive(expires, timezone.utc) + expires = timezone.make_naive(expires, datetime.timezone.utc) delta = expires - expires.utcnow() # Add one second so the date matches exactly (a fraction of # time gets lost between converting to a timedelta and diff --git a/tests/test_http.py b/tests/test_http.py index bb55ba0cd..951f4486f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -1,3 +1,4 @@ +import datetime import re from importlib import import_module @@ -33,6 +34,17 @@ async def test_set_cookie(): } +def test_set_cookie_aware_expires(): + message = {} + expires = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(hours=1) + CookieMiddleware.set_cookie( + message, "Testing-Key", "testing-value", expires=expires + ) + value = message["headers"][0][1].decode("utf-8") + max_age = int(re.search(r"Max-Age=(\d+)", value).group(1)) + assert 3599 <= max_age <= 3601 + + @pytest.mark.django_db(transaction=True) @pytest.mark.asyncio async def test_sessions():