Search code examples
pythonsessionflaskflask-session

How to set a global secret key to handle sessions in flask


I have a flask application with several blueprints names as auth,admin,user I am having one secret key in view.py of auth blueprint.

How to make this as a global key so that I can use it everywhere in the app

I set secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' in run.py file. But not working


Solution

  • You could create a new file with something like:

    # config.py
    import os
    class Config(object):
        SECRET_KEY = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
    

    And then in your flask __init__.py file import it:

    from config import Config
    # And after the flask app instanciation you do
    flask_app_instance.config.from_object(Config)
    

    This way you will only need to call it by flask_app_instance.config["SECRET_KEY"]

    EDIT: well OP found the solution, leaving this here anyway

    EDIT2:

    If you are planing to deploy your whatever you're doing you should consider not writing the secret_key inside your script and do something like this instead:

    SECRET_KEY = os.environ.get('SECRET_KEY') or 'some secret key here'
    

    This will take grab the secret key from a env var (called SECRET_KEY) from the machine the server is on