Django Projects and git

9

如何处理像Django这样的Web框架在github或其他公共域版本控制站点上的安全性。

settings.py通常包含敏感数据库信息、密码和密钥等,不能上传到存储库并以明文方式显示。

如何处理这个问题最常见且最不麻烦?


2
有很多关于这个主题的教程,但是十二要素应用程序被认为是软件开发的最佳框架之一。 - Selcuk
4个回答

6

正如@Selcuk所提到的,12因素应用程序提供了一个很好的指南,介绍了如何保护和隔离您的敏感信息。

在另一个答案中:Django设置:引发KeyError、引发ImproperlyConfigured或使用默认值?
我解释了我倾向于使用的方法,以尽可能接近12因素指南。
简而言之:

  1. 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
    ...
    
  2. Add .env and .env.* or .ini and .ini.* on your .gitignore file, thus protecting your sensitive info from been uploaded to github.
  3. Create a 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.
  4. 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')
    ...
    

经过一番探索,这种方法效果相当不错。谢谢。以下是我用来得到最终产品的一些参考链接:链接1 链接2 - addohm

0
通常我会为每个阶段(开发、测试和生产)使用不同的settings.py。唯一一个我保留在版本控制中的是对应开发的那个settings.py。其他的settings.py是内部的,需要时会被复制到服务器的每个实例(测试和生产)中。
希望这可以帮助到您。

0
简单的答案:将它添加到你的.gitignore中。话虽如此,如果你打算分享你的Django应用程序,你至少需要提供你编辑的部分。

0

密码和敏感信息存储在我的个人设置文件夹中,分别为dev_settings.pyprod_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文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接