【问题标题】:Flask session is empty after redirect重定向后 Flask 会话为空
【发布时间】:2016-06-07 07:42:12
【问题描述】:

我有这样的代码:

from flask import Flask, render_template, redirect, request, url_for, session

app = Flask(__name__)


@app.route('/')
def index():
    tmplt = session.get('template', 'No template')
    return render_template('index.html', template=tmplt.decode('utf-8'))


@app.route('/template', methods=['POST'])
def upload_template():
    session['template'] = request.files['template'].read()
    return redirect(url_for('index'))


if __name__ == '__main__':
    app.secret_key = '\x0cw1\xd4\xd5\x80%O?q \xcfQrrk\xa3H\xc0[J\xae<\xc3]\xe6\x10\xc0-\xf8S\x08P4[3]PrK\xa9\xf1'
    app.run(debug=True)

我希望,在成功执行POST /template 之后,变量tmplt 将等于上传的内容。然而,它是空的。调试显示session['template'] 在重定向之前按预期存储文件内容。

任何人都可以提出这里的问题是什么? Flask 文档和谷歌搜索没有帮助:(

【问题讨论】:

    标签: python flask


    【解决方案1】:

    sessions implementation,好像flask只是把所有的session数据都保存到cookie里了。

    根据answer,最大 cookie 大小为 4KB。如果您的文件大于该文件,则浏览器可以拒绝 cookie。

    无论如何,将文件存储到会话中看起来不是一个好主意。

    【讨论】:

    • 这么简单...谢谢!
    • 请问这个怎么做?
    • @hubert 如果您遇到上述问题(会话数据太大而无法存储在 cookie 中),那么您需要更改代码以使此数据更小 - 不要存储大将事物存入 cookie 或使用浏览器本地存储而不是 cookie 来保存用户数据(或两者兼而有之,比如在 cookie 中有用户身份信息,这样您就可以在服务器上识别用户并将用户数据缓存到本地存储中)。跨度>
    猜你喜欢
    • 2021-02-22
    • 1970-01-01
    • 2017-03-31
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多