简体   繁体   English

我应该将密钥放在 Flask 的什么位置?

[英]Where should I place the secret key in Flask?

While reading exploreflask.com , I learned that it is best practice to use two different config files, one for development and one for production.在阅读exploreflask.com 时,我了解到最好使用两种不同的配置文件,一种用于开发,一种用于生产。 I don't understand whether to place the secret key inside of the development or production config.我不明白是否将密钥放在开发或生产配置中。

The private nature of the instance folder makes it a great candidate for defining keys that you don't want exposed in version control.实例文件夹的私有性质使其成为定义不想在版本控制中公开的密钥的绝佳候选者。 These may include your app's secret key or third-party API keys.这些可能包括您应用的密钥或第三方 API 密钥。

I suppose the secret key shouldn't be shared.我想不应该共享密钥。 Should I put the secret key in the development config or the production config, or should I have a different key for each config?我应该将密钥放在开发配置还是生产配置中,还是应该为每个配置使用不同的密钥?

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.如果您没有办法在生产中添加私有文件,例如在 Heroku 上,另一种选择是使用环境变量。 If the variable is set, it overrides the default.如果设置了该变量,它将覆盖默认值。

app.secret_key = os.environ.get('SECRET_KEY', 'dev')

I use a mixture of hardcoded values and environment variables in my production config.py:我在生产 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.在我的开发 config.py 中,一切都是硬编码的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM