Where should I place the secret key in Flask?

后端 未结 2 2016
忘掉有多难
忘掉有多难 2020-11-27 22:25

While reading exploreflask.com, I learned that it is best practice to use two different config files, one for development and one for production. I don\'t understand whether

相关标签:
2条回答
  • 2020-11-27 22:47

    I use a mixture of hardcoded values and environment variables in my production config.py:

    import os
    
    
    class Config(object):
        SECRET_KEY = os.environ.get("SECRET_KEY")
        SQLALCHEMY_DATABASE_URI = os.environ.get("DB_PROD")
        SQLALCHEMY_TRACK_MODIFICATIONS = False
    

    In my development config.py, eveything is hardcoded.

    0 讨论(0)
  • 2020-11-27 23:08

    Place a secret key in the development config, which gets committed to the repo. This is convenient for developers, because they don't have to generate one to start running the app. In production, use a production config (which is never committed to the repo), with a unique secret key. The production config should override the development config.

    app = Flask(__name__, instance_relative_config=True)
    # default value during development
    app.secret_key = 'dev'
    # overridden if this file exists in the instance folder
    app.config.from_pyfile('config.py', silent=True)
    

    If you don't have a way to add private files in production, such as on Heroku, another option is to use environment variables. If the variable is set, it overrides the default.

    app.secret_key = os.environ.get('SECRET_KEY', 'dev')
    
    0 讨论(0)
提交回复
热议问题