the session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. Flask/Heroku
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.
It's likely that when your HTTP server is loading your application, __name__
is not equal to 'main'
. Try moving the line app.secret_key = 'some secret key'
outside the if block.
It's not a good idea to put your secret key in source code because if anyone gets it they can malevolently gain access to your system. Try storing it in a file in the application's instance directory (snippet here) or putting it in an environment variable (explanation here).
The exception is raised by the NullSessionInterface session implementation, which is the default session type when you use Flask-Session. That's because you don't ever actually give the SESSION_TYPE configuration to Flask; it is not enough to set it as a global in your module.
This default doesn't make much sense with Flask 0.10; it may have made sense with Flask 0.8 or 0.9, but the current version is used as an error signal. In your case it gives you the wrong error message now.
Set the SESSION_TYPE configuration option to something else. Pick one of redis, memcached, filesystem or mongodb.
Setting it to filesystem is easiest; there is enough default configuration there to have that work without additional dependencies:
if __name__ == "__main__":
app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
sess.init_app(app)
app.debug = True
app.run()