AlexMooreTech
AlexMooreTech

Reputation: 9

Python flask - Setup and open session

Trying to create login api utilizing flask session with react as the front end.

After configuring and trying to open sessions I get the below error:

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

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.

I tried following the various pieces of advice from :

  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

Any help would be greatly appreciated.

Upvotes: 0

Views: 586

Answers (1)

AlexMooreTech
AlexMooreTech

Reputation: 9

The secret key is actually being set, but is not set within the main api/.py that is being called on runtime. Moving the secret key import into the .py file being directly called on runtime resolved this issue.

Upvotes: 0

Related Questions