2013-04-05 3 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() 

이 : 나는 사용자로 로그인하는 경우이 잘 작동하고 'current_day이'세션에서 유지됩니다

 login(request, user) 

. 하지만 그 사용자로 로그 아웃하고 다른 사용자로 로그인하면 '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

관련 문제