2013-04-05 131 views
3

會話何時被創建和銷燬? 在我的應用程序有使用login()會丟失會話數據

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」仍然可以在會話但調用登錄信息(用戶)可能會創建一個新的會議。

這個假設是否正確,以及如何更好地解決這個問題?

回答

3

login source

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(或檢查與自定義的中間件每一個請求它的存在)。

+0

是的,我會按照您的建議進行操作,並在登錄後立即設置當天。 – jimscafe 2013-04-05 09:51:02