the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. Flask/Heroku

Flyn Sequeira picture Flyn Sequeira · Feb 26, 2016 · Viewed 25.4k times · Source

The flask app can login and register all fine on localhost. But this becomes an issue when i push it to heroku. It shows the above mentioned error. Here's the app.py code

from flask import Flask, render_template, request, redirect, jsonify, url_for, flash
from sqlalchemy import create_engine, asc, desc
from sqlalchemy.orm import sessionmaker
from database_setup import Base, User, BlogPost
from flask import session as login_session
import random
import string
from wtforms import Form, BooleanField, TextField, PasswordField, validators
from passlib.hash import sha256_crypt


app = Flask(__name__)


#Connecting to database
engine = create_engine('sqlite:///travellerdata.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

And ends with...

if __name__ == "__main__":
    app.secret_key = 'some secret key'
    app.debug = True
    app.run()

Answer

Yibei Huang picture Yibei Huang · Aug 18, 2016

I have the same issue when I use flask-login to generate a session ID, it works fine when I directly run it but will output error when I use HTTP server. The original code is like:

if __name__ == "__main__":
    app.secret_key = os.urandom(24)
    app.run()

Then I moved app.secret_key = os.urandom(24) out of __name__ and put it under app = Flask(__name__) like this:

app = Flask(__name__)
app.secret_key = os.urandom(24)

login_manager = flask_login.LoginManager()
login_manager.init_app(app)

And it works fine now.