简体   繁体   中英

Python - Issue with Flask and session

I want to store a user id in a session and thought it would be as simple as doing this:

session['login_id'] = data[0]

But when I run my python script I get following error message:

TypeError: 'NoneType' object has no attribute '__getitem__'

Hope someone can help me out. Thanks.

Here is the code

from flask import Flask, render_template, request, redirect, url_for, abort, session
from flaskext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

app.config['MYSQL_DATABASE_USER'] = 'username'
app.config['MYSQL_DATABASE_PASSWORD'] = 'password'
app.config['MYSQL_DATABASE_DB'] = 'database'
app.config['MYSQL_DATABASE_HOST'] = 'host'
mysql.init_app(app)

@app.route('/signin', methods=['POST'])
       def signin():
        username = request.form['txt_login']
        password = request.form['txt_pass']
        cursor = mysql.connect().cursor()
        cursor.execute("SELECT * from users where login_name='" + username + "' and password='" + password + "'")
        data = cursor.fetchone()
        session['login_id'] = int(data[0])
        if data is None:
            return render_template('authenticate.html', error="Invalid username or password")
        else:
            return redirect(url_for('home'))

if __name__ == '__main__':
    app.secret_key = 'A0Zr98jRT#142DS4#sdfs4'
    app.run(host="0.0.0.0")

The error msg is below.

File "render_template.py", line 29, in signin session['login_id'] = int(data[0]) TypeError: 'NoneType' object has no attribute ' getitem '

Have you configured the "secret_key" parameter? As you can see in the Quickstart - Flask Documentation , if you want to use session feature it is necessary to set a secret key.

Hope this can be helpful.

Ok obviously a noob in python, I had the wrong SQL query altogether. Thank you all for trying to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM