#31920: ASGI/ASYNC SessionMiddleware - SynchronousOnlyOperation exception if
request.user is not unwrapped in sync code
----------------------------------+------------------------------------
Reporter: Michael Galler | Owner: lirontb
Type: New feature | Status: assigned
Component: contrib.sessions | Version: 3.1
Severity: Normal | Resolution:
Keywords: async | Triage Stage: Accepted
Has patch: 1 | Needs documentation: 1
Needs tests: 0 | Patch needs improvement: 1
Easy pickings: 0 | UI/UX: 0
----------------------------------+------------------------------------
Comment (by Adam Johnson):
I don’t like the suggestion of adding `SimpleLazyObject.__await__`. It’s
too “magical” and it makes the type of `request.user` complex.
Currently django-stubs types `request.user` as `User | AnonymousUser`
(with a documented technique to use just `User`
[https://github.com/typeddjango/django-stubs#how-can-i-create-a
-httprequest-thats-guaranteed-to-have-an-authenticated-user for logged in
requests]). If we wanted to support the `__await__` method in type hints,
then the type would become `User | AnonymousUser | Awaitable[[], User |
AnonymousUser]`. This would require [https://adamj.eu/tech/2021/05/17
/python-type-hints-how-to-narrow-types-with-isinstance-assert-literal/
type narrowing] everywhere `request.user` is used... so, we probably
wouldn’t want to do that in django-stubs, but that would make it harder to
have a correctly type-checked async Django app.
I propose instead making the middleware add a coroutine `request.auser()`
that fetches from `request.user`, used like:
{{{
user = await request.auser()
if user.is_authenticated:
...
}}}
Yes, it’s a little more code, but it follows Django’s other async API’s
and it looks like a normal coroutine call.
--
Ticket URL: <https://code.djangoproject.com/ticket/31920#comment:13>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/0107018437d1acbc-437d0eb6-3942-4b33-bdb2-1ba344477338-000000%40eu-central-1.amazonses.com.