如何在不产生循环导入的情况下访问导入的本地设置?

2 投票
2 回答
1128 浏览
提问于 2025-04-17 06:47

在我的settings.py文件的最后,我有:

try:
    from local_settings import *
except ImportError:
    pass

然后我有一个local_settings.py文件,里面有一些数据库设置等等。在这个文件里,我还想做以下事情(为了使用django_debug_toolbar):

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

我想把这些设置放在这里,这样它们就不会出现在生产环境中,因为生产环境使用的是主settings.py文件。不过,这个文件无法访问原始的设置,因为它不知道settings.py的存在。我该如何避免可能出现的循环导入,以实现我想要的效果呢?

2 个回答

3

你不能这样做。导入的模块是在它自己的范围内执行的,它无法知道自己是在哪里被导入的,也不知道是否被导入。另一种方法可以是这样的:

在你的 local_settings 文件中:

INTERNAL_IPS = ('127.0.0.1',)
MIDDLEWARE_CLASSES = ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS = ('debug_toolbar',)

然后在主设置文件 settings.py 中:

try:
    import local_settings as local
    has_local = True
except ImportError:
    has_local = False

# ...
if has_local:
    MIDDLEWARE_CLASSES += local.MIDDLEWARE_CLASSES
3

我使用了一种方法,把我的设置做成一个包,而不是一个模块。

设置的文件结构如下:

settings/

init.py

base.py

local.py #这个文件在 .gitignore 中,意思是它不会被上传到代码仓库

init.py:

from setings import *
try:
    from local.py import *
except ImportError:
    pass

base.py:

import os
DEBUG = False
TEMPLATE_DEBUG = DEBUG

SITE_ROOT = os.path.join( os.path.dirname( os.path.realpath(__file__) ) ,'..' )

ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': '',                      # Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
    }

etc...

local.py:

from settings import settings as PROJECT_DEFAULT

PREPEND_WWW = False
DEBUG = True
TEMPLATE_DEBUG = DEBUG

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_pyscopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'somesecretname',                      # Or path to database file if using sqlite3.
        'USER': 'somesecretuser',                      # Not used with sqlite3.
        'PASSWORD': 'somesecretpassword',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

INSTALLED_APPS += PROJECT_DEFAULT.INSTALLED_APPS + ('debug_toolbar',)

你可以在 这里 查看这个例子的具体内容。

撰写回答