如何处理像Django这样的Web框架在github
或其他公共域版本控制站点上的安全性。
settings.py
通常包含敏感数据库信息、密码和密钥等,不能上传到存储库并以明文方式显示。
如何处理这个问题最常见且最不麻烦?
正如@Selcuk所提到的,12因素应用程序提供了一个很好的指南,介绍了如何保护和隔离您的敏感信息。
在另一个答案中:Django设置:引发KeyError、引发ImproperlyConfigured或使用默认值?
我解释了我倾向于使用的方法,以尽可能接近12因素指南。
简而言之:
Create a .env
or .ini
file with your project variables in it:
DB_USERNAME=myDB
DB_PASSWORD=for_your_eyes_only
DEBUG=False
MY_DJANGO_KEY=no_peeking_this_is_secret
...
.env
and .env.*
or .ini
and .ini.*
on your .gitignore
file, thus protecting your sensitive info from been uploaded to github.env.example
(be careful not to name it with a .
in the beginning, because it will get ignored). In that file you can put an example of the expected configuration in order to be re-producible by simply copy, paste, rename to .ini or .env
.Use decouple.config
to read your config file:
on settings.py
from decouple import Csv, config
DEBUG = config('DEBUG', cast=bool, default=True)
SECRET_KEY = config('MY_DJANGO_KEY')
...
settings.py
。唯一一个我保留在版本控制中的是对应开发的那个settings.py
。其他的settings.py
是内部的,需要时会被复制到服务器的每个实例(测试和生产)中。.gitignore
中。话虽如此,如果你打算分享你的Django应用程序,你至少需要提供你编辑的部分。密码和敏感信息存储在我的个人设置文件夹中,分别为dev_settings.py
和prod_settings.py
,这两个文件都在.gitignore
中。在settings.py
中,我可以通过环境变量来切换它们,如下所示:
DEV_SETTINGS = '_XXXXX_'
if os.environ.get('PROJECT_NAME_PROD', 'NO') == 'YES':
from project.prod_settings import *
else:
from project.dev_settings import *
通过这种方式,您仍然可以在存储库中使用您的settings.py文件。