如何设置单个变量的到期会话

时间:2015-04-12 05:31:28

标签: python django

有没有办法用django设置一个到期的会话变量?例如:

# user enters password to view item
request.session['session_ok'] = True

# expire this after 30 seconds, so the user has to enter in password again
request.session.set_expiry(30) # <-- Not the entire session, just the one variable

我如何使用单session_ok var? https://docs.djangoproject.com/en/1.8/topics/http/sessions/

1 个答案:

答案 0 :(得分:0)

我以一种hackish的方式解决了这个问题。我为变量设置了一个到期时间。在这种情况下,因为它是一个布尔值我只是将该变量设置为时间到期:

# set the session expiration for 30 seconds from now
request.session['session_ok'] = int(time.time() + 60)

# check if it is expired
now = int(time.time())
session_expires = request.session.get('session_ok') or 0
if session_expires > now:
    session_ok = True
else:
    session_ok = False