简体   繁体   English

Python-Flask和会话问题

[英]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: 我想在会话中存储一个用户ID,并认为这样做很简单:

session['login_id'] = data[0]

But when I run my python script I get following error message: 但是,当我运行python脚本时,出现以下错误消息:

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 ' 登录会话中的文件“ render_template.py”,第29行['login_id'] = int(data [0])TypeError:'NoneType'对象没有属性' getitem '

Have you configured the "secret_key" parameter? 您是否配置了“ secret_key”参数? As you can see in the Quickstart - Flask Documentation , if you want to use session feature it is necessary to set a secret key. 如您在快速入门-Flask文档中所见,如果要使用会话功能,则必须设置一个秘密密钥。

Hope this can be helpful. 希望这会有所帮助。

Ok obviously a noob in python, I had the wrong SQL query altogether. 好的,显然是python的新手,我完全有错误的SQL查询。 Thank you all for trying to help. 谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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