channels CookieMiddleware.set_cookie() crashes on Django 5 with an aware expires (fix PR open)

Heads-up for anyone using channels’ session/cookie middleware on Django 5.x.

CookieMiddleware.set_cookie() converts an aware expires datetime with django.utils.timezone.utc, which was deprecated in Django 4.1 and removed in 5.0. Since channels requires Django>=4.2, every install on Django 5 has this path:

import datetime
import django
from django.conf import settings
settings.configure()
django.setup()
from channels.sessions import CookieMiddleware

message = {"type": "http.response.start", "headers": []}
expires = datetime.datetime(2030, 1, 1, tzinfo=datetime.timezone.utc)
CookieMiddleware.set_cookie(message, "sessionid", "abc", expires=expires)
# AttributeError: module 'django.utils.timezone' has no attribute 'utc'

Naive datetimes and max_age are unaffected, which is probably why it hasn’t come up much.

The fix is a one-liner, using datetime.timezone.utc as Django itself does. It’s in Fix CookieMiddleware.set_cookie() with aware expires on Django 5.0+ by youssef-elaasri · Pull Request #2238 · django/channels · GitHub with a regression test (issue: CookieMiddleware.set_cookie crashes on Django 5 with an aware `expires` (timezone.utc removed) · Issue #2237 · django/channels · GitHub). If you hit this, a review or confirmation on the PR would help it along.

Until it’s released, the workaround is to pass a naive UTC datetime or use max_age instead.