(Hello, the Django documentation says that I should send feature
requests to the django-developers mailing list, so I send it here.)

I have a need to get a user object using a known session key without an
HTTP request. After reading the Django code, I did not find a clean way
to do this.

Django has the "get_user" function that requires a request object. But
it actually uses only "request.session" and nothing else. So I suggest
refactoring it something like this:

#
https://github.com/django/django/blob/master/django/contrib/auth/__init__.py
def _get_user_session_key(session):
    return get_user_model()._meta.pk.to_python(session[SESSION_KEY])

def get_user(request):
    return get_user_by_session(request.session)

def get_user_by_session_key(session_key):
    SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
    return get_user_by_session(SessionStore(session_key))

def get_user_by_session(session):
    from .models import AnonymousUser
    user = None
    try:
        user_id = _get_user_session_key(session)
        backend_path = session[BACKEND_SESSION_KEY]
    except KeyError:
        pass
    else:
        ... # the rest of the code
    return user or AnonymousUser()

Note that Django Channels has similar code so the "get_user_by_session"
function can help to deduplicate it:
https://github.com/django/channels/tree/master/channels/auth.py#L23

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" 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-developers/858abfe1-42b9-185b-e69c-c23d6058e762%40andreymal.org.
  • Featur... 'andreymal' via Django developers (Contributions to Django itself)
    • R... Adam Johnson
      • ... Jani Tiainen
      • ... 'andreymal' via Django developers (Contributions to Django itself)
        • ... Adam Johnson

Reply via email to