获取密钥"错误:__ getitem__ = lambda x,i:x._get_current_object()[i] KeyError:' token_expires'"

时间:2015-09-07 13:49:19

标签: python lambda flask

我在烧瓶代码中收到KeyError。在以下函数中,authenticated_resource用于基于令牌的身份验证。在这里,我用当前时间检查令牌过期时间,看看过期时间是否大于当前时间,然后它将转发到资源,否则转发到登录页面。

KeyError位于expires=datetime.strptime(...)

File "/usr/lib/python2.7/site-packages/werkzeug/local.py", line 368, in <lambda>
    __getitem__ = lambda x, i: x._get_current_object()[i]
KeyError: 'token_expires'

我搜索了答案,并且提到如果密钥不存在则会发生此错误。所以我在expires=datetime.strptime

之前添加了两行代码
print 'Key exists or not=',flask_session.get("authenticated")
print 'expire =', datetime.strptime(flask_session['token_expires'],'%Y-%m-%dT%H:%M:%SZ')

其中给出以下结果

Key exits or not= True  
expire = 2015-09-07 15:17:2**2  

因此存在。为什么会这样?

from flask import session as flask_session, abort
from functools import wraps
from datetime import datetime
def authenticated_resource(function):
    @wraps(function)
    def decorated(*args, **kwargs):
        now= datetime.utcnow().replace(microsecond=0)
        print 'flask_session["token_expires"]=', flask_session['token_expires']
        expires=datetime.strptime(flask_session['token_expires'],'%Y-%m-%dT%H:%M:%SZ')

        print 'expires=', expires
        #expires= '2015-09-07 13:51:10'
        #print 'now=', now
        if expires <= now:  # If token is already expires 
          #print 'yes'
          flask_session.pop("auth_token", None) # Destroying the token
          flask_session.pop("authenticated", None)
          return redirect(url_for('login'))
        if flask_session.get("authenticated"):  # if token is not expires
          return function(*args, **kwargs)
        return redirect(url_for('login')) # unauthenticated
    return decorated

0 个答案:

没有答案