gpt4 book ai didi

python - 最后访问页面的 Flask 列表 AttributeError : 'Nonetype' object has no attribute 'set_cookie'

转载 作者:太空宇宙 更新时间:2023-11-03 14:52:15 25 4
gpt4 key购买 nike

我正在尝试使用 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对我来说看起来不错。

关于python - 最后访问页面的 Flask 列表 AttributeError : 'Nonetype' object has no attribute 'set_cookie' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45816424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com