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

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

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


当前回答

我使用了上面提到的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文件。

其他回答

我发现这里的回答很有帮助。(这个问题是否得到了更明确的解决?上一次回复是在一年前。)在考虑了列出的所有方法之后,我提出了一个在这里没有列出的解决方案。

我的标准是:

所有东西都应该在源代码控制中。我不喜欢精细的东西到处乱放。 理想情况下,将设置保存在一个文件中。如果我不看东西,我就会忘记它们:) 无需部署手动编辑。应该能够用一个fabric命令测试/推送/部署。 避免将开发设置泄漏到生产环境中。 让Django布局尽可能接近“标准”(*咳嗽*)。

我认为打开主机是有意义的,但后来发现真正的问题是针对不同环境的不同设置,并有了一个顿悟时刻。我把这段代码放在settings.py文件的末尾:

try:
    os.environ['DJANGO_DEVELOPMENT_SERVER'] # throws error if unset
    DEBUG = True
    TEMPLATE_DEBUG = True
    # This is naive but possible. Could also redeclare full app set to control ordering. 
    # Note that it requires a list rather than the generated tuple.
    INSTALLED_APPS.extend([
        'debug_toolbar',
        'django_nose',
    ])
    # Production database settings, alternate static/media paths, etc...
except KeyError: 
    print 'DJANGO_DEVELOPMENT_SERVER environment var not set; using production settings'

这样,应用程序默认为产品设置,这意味着你明确地将你的开发环境“白名单”。忘记在本地设置环境变量要比反过来忘记在生产环境中设置一些内容而使用一些开发设置安全得多。

在本地开发时,无论是在shell中,还是在.bash_profile中,或者其他任何地方:

$ export DJANGO_DEVELOPMENT_SERVER=yep

(或者如果你在Windows上开发,可以通过控制面板或者其他什么工具来设置…Windows总是让它变得如此模糊,以至于你可以设置环境变量。)

使用这种方法,开发设置都在一个(标准)位置,只需在需要的地方覆盖生产设置。任何与开发设置有关的事情都应该完全安全地提交到源代码控制中,而不会对生产产生影响。

我将我的设置拆分如下

settings/
     |
     |- base.py
     |- dev.py
     |- prod.py  

我们有三种环境

dev 暂存 生产

现在,显然登台和生产应该有尽可能相似的环境。所以我们同时保留了prod.py。

但是在这种情况下,我必须确定正在运行的服务器是生产服务器。@T。斯通的回答帮助我写了如下支票。

from socket import gethostname, gethostbyname  
PROD_HOSTS = ["webserver1", "webserver2"]

DEBUG = False
ALLOWED_HOSTS = [gethostname(), gethostbyname(gethostname()),]


if any(host in PROD_HOSTS for host in ALLOWED_HOSTS):
    SESSION_COOKIE_SECURE = True
    CSRF_COOKIE_SECURE = True  

我在django split-settings的帮助下管理我的配置。

它是默认设置的临时替换。它很简单,但可配置。并且不需要重构现有设置。

下面是一个小例子(文件示例/settings/__init__.py):

from split_settings.tools import optional, include
import os

if os.environ['DJANGO_SETTINGS_MODULE'] == 'example.settings':
    include(
        'components/default.py',
        'components/database.py',
        # This file may be missing:
        optional('local_settings.py'),

        scope=globals()
    )

就是这样。

更新

我写了一篇关于用django-split-sttings管理django设置的博文。看看吧!

我在manage.py中区分它,并创建了两个单独的设置文件:local_settings.py和prod_settings.py。

在manage.py中检查服务器是本地服务器还是生产服务器。如果它是本地服务器,它将加载local_settings.py,如果它是生产服务器,它将加载prod_settings.py。基本上是这样的:

#!/usr/bin/env python
import sys
import socket
from django.core.management import execute_manager 

ipaddress = socket.gethostbyname( socket.gethostname() )
if ipaddress == '127.0.0.1':
    try:
        import local_settings # Assumed to be in the same directory.
        settings = local_settings
    except ImportError:
        import sys
        sys.stderr.write("Error: Can't find the file 'local_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" % __file__)
        sys.exit(1)
else:
    try:
        import prod_settings # Assumed to be in the same directory.
        settings = prod_settings    
    except ImportError:
        import sys
        sys.stderr.write("Error: Can't find the file 'prod_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 prod_settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
        sys.exit(1)

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

我发现将设置文件分开到两个单独的文件中更容易,而不是在设置文件中做大量的if。

为了在不同的环境中使用不同的设置配置,创建不同的设置文件。在部署脚本中,使用——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.