Forums

How to set secret key for Flask-Session

I am using the following snippet at the end of my Flask app's app.py file on my local dev environment:

if __name__ == '__main__':
    app.secret_key = 'SECRET KEY'
    app.run(port=5001, debug=True)

I would need to add the app.secret_key = 'SECRET KEY' line to my production app, but I'm not sure where should I place it since my PA Flask app doesn't use the if __name__ == '__main__': condition. Is it ok if I just add it to the end of my app.py file? Or is there any other recommended solution? This code is needed to setup the Flask-Session sessions. I would really appreciate if somebody could confirm me that I am doing the right solution or not.

Don't do it in that section. That if statement is there to prevent that code from running when you are not running the Python file as a script, so it does not get run in a web app.

Thanks Glenn! What do you think, how should I do that? Can I keep it in the same if statment without the app.run(port=5001, debug=True) line?

pumpuma, you may want to check out the Flask docs on deployment. They specifically talk about where to set your SECRET_KEY.

gregkaleka, thanks! I checked the docs but it seems for me that it's not the same type of secret key I am using. It's needed for the Flask-Session lib which is not the simple session handler.

Ah I see - sorry, I jumped on that too quickly :)

@pumpuma -- presumably there's some code where you set up the Flask-Session library -- eg. by running something like

Session(app)

This will be near the top of your code, probably just after you've done the traditional

app = Flask(__name__)

I'd suggest putting the code to set the session_key just before you do the Session(app).

Thanks Giles! I will do that way.