Thomas
Thomas

Reputation: 1212

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

I'm trying to verify a user using flask session. The problem is that whenever I try to assign a value to my session, I get the error:

TypeError: 'type' object does not support item assignment

I have seen This stack overflow question and I have been using guides such as this one, however I have been unable to solve this problem.

Code:

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')

I thought that my error could have been related to request.form['un'], so I changed the code to:

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 is setup like this:

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)

If this is something silly then I apologize for wasting your time :). I would appreciate any help. Thanks

Upvotes: 1

Views: 1711

Answers (1)

Rafael Marques
Rafael Marques

Reputation: 1876

You are trying to assign the value to Session object.

If you check the example on the project's repo, you'll see it assigns the value to flask session, not flask_session's Session object:

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)

Upvotes: 1

Related Questions