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

标签 python flask

我正在尝试使用 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/

相关文章:

python - 从数据库或 session 数据填充字段的正确方法是什么?

python - 用 DispatcherMiddleware 包裹的 Flask 应用不再有 test_client

python - 修改 Celery 节拍计划搁置数据库

python - 使用 NCO 扩展 netCDF 文件的尺寸

python - 使用 $(shell ...) 从 makefile 执行 python

python如何导入脚本

python - 没有使用 virtualenv 的名为 flask 的模块

python - 使用 Flask wtforms 创建自定义小部件

python - Flask 猜谜游戏无法正确响应

python - pandas to_csv — 不编码文件名或路径