我有这样的代码:
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)
Run Code Online (Sandbox Code Playgroud)
我预计,成功执行后POST /template,变量tmplt将等于上传的内容。然而,它是空的。调试显示session['template']在重定向之前按照预期存储了文件内容。
任何人都可以建议这里有什么问题吗?Flask 文档和谷歌搜索没有帮助:(
从session的实现来看,flask似乎只是将所有的session数据保存到cookie中。
根据这个答案,最大的 cookie 大小是 4KB。如果您的文件大于该值,则浏览器可以拒绝 cookie。
无论如何,将文件存储到会话中看起来都不是一个好主意。