1

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

设置/初始化.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
4

1 回答 1

4

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

拥有一个settings.py文件更容易,其中包含生产服务器的所有设置以及所有开发机器通用的设置,并local_settings.py在其底部导入。这local_settings.py将是开发人员添加特定于他们机器的设置的地方。

设置.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文件。

于 2011-10-15T11:40:55.147 回答