Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the async session.asave method if it exists #2092

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

bigfootjon
Copy link
Contributor

Support was added in django/django#17372 (slated for release in 5.1)

We can use this API if it exists, otherwise, we fallback to a sync_to_async bridge.

This does break backwards compatibility, which I'm not terribly happy about but I'm not sure how best to fix it.

If users overrode save_session in a subclass they would expect that to still work, so I thought the best way to do this was to make it async in the base class and then await it, so at least it will be obvious that it doesn't work (python will raise an exception about awaiting a non-awaitable), but I'm open to other solutions.

channels/sessions.py Outdated Show resolved Hide resolved
if django.VERSION >= (5, 1):
await self.scope["session"].asave()
else:
await database_sync_to_async(self.scope["session"].save)()
except UpdateError:
raise SuspiciousOperation(
"The request's session was deleted before the "
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not actually sure how to trigger this logic, because based on reading the Django source code I can't figure out where it would be raised when calling save() without must_create=True

@bigfootjon
Copy link
Contributor Author

@carltongibson: I've added the missing test coverage (such as I could, see inline comment) and fixed the thing you noted.

I'm not sure this should be merged before #2090 is resolved since sessions can use the Django ORM under the hood.

@carltongibson
Copy link
Member

Yes, I too was thinking we need to settle that first 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants