secret key not set in flask session, using the Flask-Session extension secret key not set in flask session, using the Flask-Session extension python python

secret key not set in flask session, using the Flask-Session extension


In your case 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. The Flask-Session quickstart example code does set a global, but then uses the current module as a configuration object by calling app.config.from_object(__name__).

This default doesn't make much sense with Flask 0.10 or newer; NullSession may have made sense with Flask 0.8 or 0.9, but in current version the flask.session.NullSession class 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, and make sure to set it in app.config (directly or via the various Config.from_* methods).

For a quick test, setting it to filesystem is easiest; there is enough default configuration there to have that work without additional dependencies:

if __name__ == "__main__":    # Quick test configuration. Please use proper Flask configuration options    # in production settings, and use a separate file or environment variables    # to manage the secret key!    app.secret_key = 'super secret key'    app.config['SESSION_TYPE'] = 'filesystem'    sess.init_app(app)    app.debug = True    app.run()

If you see this error and you are not using Flask-Session, then something has gone wrong with setting the secret. If you are setting app.config['SECRET_KEY'] or app.secret_key in a if __name__ == "__main__": guard like above and you get this error, then you are probably running your Flask app via a WSGI server that imports your Flask project as a module, and the __name__ == "__main__" block is never run.

It is always better to manage configuration for Flask apps in a separate file, anyway.


Set the secret key outside of if __name__ == '__main__':

app.py:

from flask import Flask, sessionapp = Flask(__name__)app.secret_key = "super secret key"@app.route("/")...if __name__ == '__main__':    app.debug = True    app.run()

When you start your app by running flask run the if __name__ == '__main__': block gets skipped. If you don't want to skip it, run with python app.py.


Try this:

app = Flask(__name__)app.config['SESSION_TYPE'] = 'memcached'app.config['SECRET_KEY'] = 'super secret key'sess = Session()

And remove your app.secret_key assignment at the bottom.