简体   繁体   English

Python flask - 设置并打开 session

[英]Python flask - Setup and open session

Trying to create login api utilizing flask session with react as the front end.尝试使用 flask session 作为前端创建登录 api。

After configuring and trying to open sessions I get the below error:配置并尝试打开会话后,我收到以下错误:

RuntimeError: The session is unavailable because no secret key was set. RuntimeError:session 不可用,因为未设置密钥。 Set the secret_key on the application to something unique and secret.将应用程序上的 secret_key 设置为唯一且机密的东西。

The code is as follows:代码如下:

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

I have tried various formats for setting flask sessions and for setting secret key to no avail.我尝试了各种格式来设置 flask 会话和设置密钥无济于事。

I tried following the various pieces of advice from:我尝试遵循以下各种建议:

  1. secret key not set in flask session, using the Flask-Session extension 未在 flask session 中设置密钥,使用 Flask-Session 扩展
  2. https://www.geeksforgeeks.org/how-to-use-flask-session-in-python-flask/ https://www.geeksforgeeks.org/how-to-use-flask-session-in-python-flask/
  3. https://www.py4u.net/discuss/156106 https://www.py4u.net/discuss/156106

Any help would be greatly appreciated.任何帮助将不胜感激。

The secret key is actually being set, but is not set within the main api/.py that is being called on runtime.密钥实际上正在设置,但未在运行时调用的主 api/.py 中设置。 Moving the secret key import into the.py file being directly called on runtime resolved this issue.将密钥导入移动到运行时直接调用的 .py 文件中解决了这个问题。

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

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