与多个开发人员一起管理django本地和站点设置?

时间:2011-10-14 22:52:24

标签: django settings dev-to-production

环顾四周之后,我想出了以下代码,这似乎运作良好,我想知道其他人提出了什么,反馈会很棒。

设置/的初始化的.py

import sys
import socket

# try to import settings file based on machine name.
try:
    settings = sys.modules[__name__]
    host_settings_module_name = '%s' % (socket.gethostname().replace('.', '_'))
    host_settings = __import__(host_settings_module_name, globals(), locals(), ['*'], -1)
    # Merge imported settings over django settings
    for key in host_settings.__dict__.keys():
        if key.startswith('_'): continue #skip privates and __internals__
        settings.__dict__[key] = host_settings.__dict__[key]

except Exception, e:
    print e
    from settings.site import *

设置/ base.py

BASE = 1
SITE = 1
LOCAL = 1

settings / site.py //项目特定

from settings.base import *
SITE = 2
LOCAL = 2

settings / machine_name_local.py //开发人员或主机服务器的计算机专用设置

from settings.site import *
LOCAL = 3

1 个答案:

答案 0 :(得分:4)

我认为虽然您的代码可能有效,但它不必要地复杂化。复杂的代码很少是一件好事,因为它很难调试,而你的设置模块在最后一个地方你想在Django项目中引入错误。

拥有settings.py文件更容易,生成服务器的所有设置加上所有开发机器通用的设置,并在其底部导入local_settings.py。然后local_settings.py将成为开发人员添加特定于其计算机的设置的地方。

<强> settings.py

# all settings for the production server, 
# and settings common to all development machines eg. 
# INSTALLED_APPS, TEMPLATE_DIRS, MIDDLEWARE_CLASSES etc.

# Import local_settings at the very bottom of the file
# Use try|except block since we won't have this on the production server, 
# only on dev machines
try:
    from local_settings import *
except ImportError:
    pass

<强> local_settings.py

# settings specific to the dev machine
# eg DATABASES, MEDIA_ROOT, etc
# You can completely override settings in settings.py 
# or even modify them eg:

from settings import INSTALLED_APPS, MIDDLEWARE_CLASSES # Due to how python imports work, this won't cause a circular import error

INSTALLED_APPS += ("debug_toolbar",)
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)

只需记住在生产服务器上上传local_settings.py,如果您使用的是VCS,请对其进行配置,以便忽略local_settings.py文件。< / p>