flask session - TypeError: 'type' object does not support item assignment

flask session - TypeError: 'type' object does not support item assignment

我正在尝试使用 Flask 会话验证用户。问题是每当我尝试为我的会话分配一个值时,我都会收到错误消息:

TypeError: 'type' object does not support item assignment

我看到了 and I have been using guides such as this one,但是一直无法解决这个问题

代码:

from flask import Flask, redirect, url_for, request, render_template
from flask_session import Session
if request.method == 'POST':
    username = request.form['un']
    password = request.form['pw']
    Session['name'] = request.form['un'] #this is where my error is occuring
else:
    username = request.args.get('un')
    password = request.args.get('pw')
    Session["name"] = request.args.get('un')

我认为我的错误可能与request.form['un']有关,所以我将代码更改为:

from flask import Flask, redirect, url_for, request, render_template
from flask_session import Session
if request.method == 'POST':
    username = request.form['un']
    password = request.form['pw']
    Session['test'] = 'test' #still have an error here
else:
    username = request.args.get('un')
    password = request.args.get('pw')
    Session["test"] = "test"

应用程序是这样设置的:

app = Flask(__name__, template_folder='template')
app.config["SESSION_PERMANENT"] = True
app.config["SESSION_TYPE"] = "filesystem"
app.secret_key = 'why would I tell you my secret key?'
app.config.from_object(__name__)
Session(app)

如果这是愚蠢的事情,那么我很抱歉浪费你的时间 :)。我将不胜感激任何帮助。 谢谢

您正在尝试将值分配给 Session 对象。

如果您检查 project's repo, you'll see it assigns the value to flask session 上的示例,而不是 flask_session 的 Session 对象:

from flask import Flask, session
from flask_session import Session


SESSION_TYPE = 'redis'


app = Flask(__name__)
app.config.from_object(__name__)
Session(app)


@app.route('/set/')
def set():
    # check here
    # it is flask's session, not flask_session's Session object
    session['key'] = 'value'
    return 'ok'


@app.route('/get/')
def get():
    return session.get('key', 'not set')


if __name__ == "__main__":
    app.run(debug=True)