3

会话何时创建和销毁?在我的应用程序中,我有

def app_login(request):
    request.session.set_expiry(0)
    if 'current_day' not in request.session:
        request.session['current_day'] = Utilities.default_day()

然后再往下我使用:

     login(request, user)

如果我以用户身份登录,这可以正常工作,并且“current_day”会保留在会话中。但是,如果我以该用户身份注销并以另一个用户身份登录,则“current_day”将丢失,并且在调用 login() 后无法立即使用。

我假设

logout(request)

不会清除会话,并且当第二个用户尝试登录时,数据“current_'day”在会话中仍然可用,但调用 login(user) 可能会创建一个新会话。

这个假设是否正确以及如何最好地纠正这个假设?

4

1 回答 1

5

登录源

def login(request, user):
    """
    Persist a user id and a backend in the request. This way a user doesn't
    have to reauthenticate on every request. Note that data set during
    the anonymous session is retained when the user logs in.
    """
    if user is None:
        user = request.user
    # TODO: It would be nice to support different login methods, like signed cookies.
    if SESSION_KEY in request.session:
        if request.session[SESSION_KEY] != user.pk:
            # To avoid reusing another user's session, create a new, empty
            # session if the existing session corresponds to a different
            # authenticated user.
            request.session.flush()
    else:
        request.session.cycle_key()
    request.session[SESSION_KEY] = user.pk
    request.session[BACKEND_SESSION_KEY] = user.backend
    if hasattr(request, 'user'):
        request.user = user
    user_logged_in.send(sender=user.__class__, request=request, user=user)

匿名会话被保留(它们没有SESSION_KEY),作为不同的用户刷新会话重新登录。

注销也会刷新会话:

def logout(request):
    """
    Removes the authenticated user's ID from the request and flushes their
    session data.
    """
    # Dispatch the signal before the user is logged out so the receivers have a
    # chance to find out *who* logged out.
    user = getattr(request, 'user', None)
    if hasattr(user, 'is_authenticated') and not user.is_authenticated():
        user = None
    user_logged_out.send(sender=user.__class__, request=request, user=user)

    request.session.flush()
    if hasattr(request, 'user'):
        from django.contrib.auth.models import AnonymousUser
        request.user = AnonymousUser()

这是刷新会话时仅有的两种情况。

 

您应该current_day在登录后设置(或使用自定义中间件检查每个请求是否存在)。

于 2013-04-05T08:44:01.187 回答