Python flask - 设置和打开会话

Python flask - Setup and open session

正在尝试创建登录 api 利用 Flask 会话作为前端。

配置并尝试打开会话后,出现以下错误:

RuntimeError: The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret.

代码如下:

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

我尝试了各种格式来设置 flask 会话和设置密钥都无济于事。

我尝试遵循来自 :

的各种建议
  1. secret key not set in flask session, using the Flask-Session extension
  2. https://www.geeksforgeeks.org/how-to-use-flask-session-in-python-flask/
  3. https://www.py4u.net/discuss/156106

如有任何帮助,我们将不胜感激。

实际上正在设置密钥,但未在运行时调用的主 api/.py 中设置。将密钥导入移动到运行时直接调用的 .py 文件解决了这个问题。