【发布时间】:2022-01-06 23:34:49
【问题描述】:
尝试使用flask会话创建登录api,并以react为前端。
配置并尝试打开会话后,我收到以下错误:
RuntimeError:会话不可用,因为未设置密钥。将应用程序上的 secret_key 设置为唯一且机密的内容。
代码如下:
from flask import *
from flaskext.mysql import MySQL
from flask_session import Session
import re
#Initialise the app:
app = Flask(__name__)
#Set the secret key:
app.config['SECRET_KEY'] = 'secret key'
app.config['SESSION_TYPE'] = 'filesystem'
app.config.from_object(__name__)
Session(app)
#Setup the MySQL connection:
mysql = MySQL()
app.config['MYSQL_DATABASE_HOST'] = 'host.host'
app.config['MYSQL_DATABASE_USER'] = 'user'
app.config['MYSQL_DATABASE_PASSWORD'] = 'pass'
app.config['MYSQL_DATABASE_DB'] = 'db_name'
mysql.init_app(app)
#Log the user in:
def login(Email, Password):
#Check if the required parameters are provided in a POST request:
if request.method == 'POST' and 'email' in request.form and 'password' in request.form:
#Set the variables:
email = Email
password = Password
#Create the curser:
conn = mysql.connect()
cursor =conn.cursor()
cursor.execute('SELECT * FROM staffDetails WHERE staff_email_address = %s AND staff_password = %s', (email, password,))
#Fetch the result:
account = cursor.fetchone()
#If there is a restult:
if account:
#Create the session:
session['loggedin'] = True
session['id'] = account['id']
session['firstname'] = account['firstname']
#Resturn the result:
return jsonify({'status' : 'Ok'})
else:
#Return an error:
return jsonify({'status' : 'No', 'reason' : 'NotExist'})
我尝试了各种格式来设置烧瓶会话和设置密钥都无济于事。
我尝试了以下各种建议:
- secret key not set in flask session, using the Flask-Session extension
- https://www.geeksforgeeks.org/how-to-use-flask-session-in-python-flask/
- https://www.py4u.net/discuss/156106
任何帮助将不胜感激。
【问题讨论】:
-
我不是专家,但您希望
app.config.from_object(__name__)做什么?我希望看到一个使用属性定义的配置类,并且应用程序配置的形式为app.config.from_object(Config) -
@askman 我认为 app.config.from_object(name) 可能会导致应用程序在阅读 flask-session.readthedocs.io/en/latest 的烧瓶文档时注册文件的配置,它是更多的是实验而不是实际使用,正如您所说,确实应该用于链接到外部配置。
标签: python flask flask-session