为本地开发和生产服务器处理设置的推荐方法是什么?其中一些(如常量等)可以在两者中更改/访问,但其中一些(如静态文件的路径)需要保持不同,因此不应该在每次部署新代码时都重写。

目前,我正在将所有常量添加到settings.py中。但是每次我在本地更改一些常量时,我都必须将其复制到生产服务器并编辑文件以进行特定于生产的更改……:(

编辑:看起来这个问题没有标准答案,我已经接受了最流行的方法。


当前回答

创建多个版本的settings.py是12因素应用程序方法论的反模式。 请使用python- decoupling或django-environ。

其他回答

还有Django Classy Settings。我个人是它的忠实粉丝。它是由Django IRC上最活跃的人之一构建的。你可以使用环境变量来设置。

http://django-classy-settings.readthedocs.io/en/latest/

我使用了上面提到的jpartogi的一个变体,我觉得它更简短:

import platform
from django.core.management import execute_manager 

computername = platform.node()

try:
  settings = __import__(computername + '_settings')
except ImportError: 
  import sys
  sys.stderr.write("Error: Can't find the file '%r_settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file local_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % (computername, __file__))
  sys.exit(1)

if __name__ == "__main__":
  execute_manager(settings)

基本上,在每台计算机(开发或生产)上,我都有适当的动态加载的hostname_settings.py文件。

我使用settings_local.py和settings_production.py。在尝试了几个选项后,我发现当简单地拥有两个设置文件时,很容易在复杂的解决方案上浪费时间。

当你在Django项目中使用mod_python/mod_wsgi时,你需要将它指向你的设置文件。如果你把它指向本地服务器上的app/settings_local.py和生产服务器上的app/settings_production.py,那么事情就变得简单了。只需编辑适当的设置文件并重新启动服务器(Django开发服务器将自动重新启动)。

为了在不同的环境中使用不同的设置配置,创建不同的设置文件。在部署脚本中,使用——settings=<my-settings.py>参数启动服务器,通过该参数可以在不同的环境中使用不同的设置。

使用这种方法的好处:

Your settings will be modular based on each environment You may import the master_settings.py containing the base configuration in the environmnet_configuration.py and override the values that you want to change in that environment. If you have huge team, each developer may have their own local_settings.py which they can add to the code repository without any risk of modifying the server configuration. You can add these local settings to .gitnore if you use git or .hginore if you Mercurial for Version Control (or any other). That way local settings won't even be the part of actual code base keeping it clean.

不要使用settings.py,而是使用下面的布局:

.
└── settings/
    ├── __init__.py  <= not versioned
    ├── common.py
    ├── dev.py
    └── prod.py

py是您的大部分配置所在的位置。

py从common中导入所有内容,并覆盖它需要覆盖的内容:

from __future__ import absolute_import # optional, but I like it
from .common import *

# Production overrides
DEBUG = False
#...

类似地,dev.py从common.py导入所有内容,并覆盖它需要覆盖的内容。

最后,__init__.py是你决定加载哪些设置的地方,也是你存储秘密的地方(因此这个文件不应该被版本化):

from __future__ import absolute_import
from .prod import *  # or .dev if you want dev

##### DJANGO SECRETS
SECRET_KEY = '(3gd6shenud@&57...'
DATABASES['default']['PASSWORD'] = 'f9kGH...'

##### OTHER SECRETS
AWS_SECRET_ACCESS_KEY = "h50fH..."

我喜欢这个解决方案的原因是:

所有东西都在您的版本控制系统中,除了机密信息 大多数配置都在一个地方:common.py。 特定于产品的东西放在prod。py中,特定于开发的东西放在dev。py中。这很简单。 你可以在prod.py或dev.py中覆盖common.py中的内容,也可以覆盖__init__.py中的任何内容。 这是简单的python。没有重新导入黑客。