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、開発者が自分のマシンに固有の設定を追加する場所になります。

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ファイルが無視されるように構成してください。

于 2011-10-15T11:40:55.147 に答える