我正在尝试使用 session 创建最近访问的页面的列表。我不断收到错误 AttributeError: 'Nonetype' object has no attribute 'set_cookie'
我认为 @app.after_request
部分是原因,但我不知道如何修复它。
Python代码
@app.route('/')
def index():
session['urls'] = []
data = []
if 'urls' in session:
data = session['urls']
timestamp = None
t = time.strftime("%H:%M:%S")
(h, m, s) = t.split(':')
result = int(h) * 3600 + int(m) * 60 + int(s)
if 0 <= result < 43200:
timestamp = 'Goedemorgen'
elif 43200 <= result < 64800:
timestamp = 'Goedemiddag'
elif 64800 <= result:
timestamp = 'Goedeavond'
resp = make_response(render_template('index.html', timestamp=timestamp, data=data))
resp.set_cookie('visited', 'visited', expires=datetime.datetime.now() + datetime.timedelta(days=2))
return resp
@app.after_request
def store_visited_urls(self):
session['urls'].append(request.url)
if(len(session['urls']) > 5):
session['urls'].pop(0)
AttributeError: 'Nonetype' object has no attribute 'set_cookie'
上述错误表明对象resp
具有Nonetype
,这意味着make_response
返回None
。这将我带到您的 make_response
函数,除了您通过它传递的参数之外,该函数很好。
问题出在这里:
def index():
session['urls'] = []
每当您调用 '/'
的请求时,您都会将 sessions['url']
初始化为空列表,因此数据在以下内容中也不会得到任何内容声明:
if 'urls' in session:
data = session['urls']
您需要单独初始化 sessions['url']
,然后在 index()
函数中使用它。
话虽如此,我假设您已将 app.secret_key
设置为您的某个 secret key 。
你的after_request
对我来说看起来不错。
我是一名优秀的程序员,十分优秀!