如何根据环境从settings.py DATABASES数组激活数据库设置?

时间:2019-01-25 20:51:49

标签: python django database python-3.x settings

我正在将Django与Python 3.7结合使用。我有一个settings.py文件,其中包含一些数据库设置...

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mainpage',
        'USER': 'mainpage',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '5432'
    },
    'production': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mainpage',
        'USER': 'mainpage',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '5432'
    }
}

该文件包含许多其他内容,但是我仅在此处包含数据库数组。是否可以根据环境或环境变量从阵列中激活特定的数据库配置?我不希望有多个设置文件,因为那样我就必须在其中重复许多不会随环境变化的其他配置。如果需要的话,我很乐意将数据库设置移动到他们自己的文件中,但是我不确定如何激活它们。

编辑:根据Scott Skiles的回答,这是我删除settings.py并添加其他目录和文件时遇到的错误,但是在加载Python控制台时出现此错误...

  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__
    self._setup(name)
  File "/Users/davea/Documents/workspace/mainpage_project/venv/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup
    % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

这是我的 init .py文件。自从项目创建以来,我一直没有改变它。

"""
Settings and configuration for Django.

Read values from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global_settings.py
for a list of all possible variables.
"""

import importlib
import os
import time
import warnings
from pathlib import Path

from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import RemovedInDjango30Warning
from django.utils.functional import LazyObject, empty

ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"


class LazySettings(LazyObject):
    """
    A lazy proxy for either global Django settings or a custom settings object.
    The user can manually configure settings prior to using them. Otherwise,
    Django uses the settings module pointed to by DJANGO_SETTINGS_MODULE.
    """
    def _setup(self, name=None):
        """
        Load the settings module pointed to by the environment variable. This
        is used the first time settings are needed, if the user hasn't
        configured settings manually.
        """
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        if not settings_module:
            desc = ("setting %s" % name) if name else "settings"
            raise ImproperlyConfigured(
                "Requested %s, but settings are not configured. "
                "You must either define the environment variable %s "
                "or call settings.configure() before accessing settings."
                % (desc, ENVIRONMENT_VARIABLE))

        self._wrapped = Settings(settings_module)

    def __repr__(self):
        # Hardcode the class name as otherwise it yields 'Settings'.
        if self._wrapped is empty:
            return '<LazySettings [Unevaluated]>'
        return '<LazySettings "%(settings_module)s">' % {
            'settings_module': self._wrapped.SETTINGS_MODULE,
        }

    def __getattr__(self, name):
        """Return the value of a setting and cache it in self.__dict__."""
        if self._wrapped is empty:
            self._setup(name)
        val = getattr(self._wrapped, name)
        self.__dict__[name] = val
        return val

    def __setattr__(self, name, value):
        """
        Set the value of setting. Clear all cached values if _wrapped changes
        (@override_settings does this) or clear single values when set.
        """
        if name == '_wrapped':
            self.__dict__.clear()
        else:
            self.__dict__.pop(name, None)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        """Delete a setting and clear it from cache if needed."""
        super().__delattr__(name)
        self.__dict__.pop(name, None)

    def configure(self, default_settings=global_settings, **options):
        """
        Called to manually configure the settings. The 'default_settings'
        parameter sets where to retrieve any unspecified values from (its
        argument must support attribute access (__getattr__)).
        """
        if self._wrapped is not empty:
            raise RuntimeError('Settings already configured.')
        holder = UserSettingsHolder(default_settings)
        for name, value in options.items():
            setattr(holder, name, value)
        self._wrapped = holder

    @property
    def configured(self):
        """Return True if the settings have already been configured."""
        return self._wrapped is not empty


class Settings:
    def __init__(self, settings_module):
        # update this dict from global settings (but only for ALL_CAPS settings)
        for setting in dir(global_settings):
            if setting.isupper():
                setattr(self, setting, getattr(global_settings, setting))

        # store the settings module in case someone later cares
        self.SETTINGS_MODULE = settings_module

        mod = importlib.import_module(self.SETTINGS_MODULE)

        tuple_settings = (
            "INSTALLED_APPS",
            "TEMPLATE_DIRS",
            "LOCALE_PATHS",
        )
        self._explicit_settings = set()
        for setting in dir(mod):
            if setting.isupper():
                setting_value = getattr(mod, setting)

                if (setting in tuple_settings and
                        not isinstance(setting_value, (list, tuple))):
                    raise ImproperlyConfigured("The %s setting must be a list or a tuple. " % setting)
                setattr(self, setting, setting_value)
                self._explicit_settings.add(setting)

        if not self.SECRET_KEY:
            raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")

        if self.is_overridden('DEFAULT_CONTENT_TYPE'):
            warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)

        if hasattr(time, 'tzset') and self.TIME_ZONE:
            # When we can, attempt to validate the timezone. If we can't find
            # this file, no check happens and it's harmless.
            zoneinfo_root = Path('/usr/share/zoneinfo')
            zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
            if zoneinfo_root.exists() and not zone_info_file.exists():
                raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
            # Move the time zone info into os.environ. See ticket #2315 for why
            # we don't do this unconditionally (breaks Windows).
            os.environ['TZ'] = self.TIME_ZONE
            time.tzset()

    def is_overridden(self, setting):
        return setting in self._explicit_settings

    def __repr__(self):
        return '<%(cls)s "%(settings_module)s">' % {
            'cls': self.__class__.__name__,
            'settings_module': self.SETTINGS_MODULE,
        }


class UserSettingsHolder:
    """Holder for user configured settings."""
    # SETTINGS_MODULE doesn't make much sense in the manually configured
    # (standalone) case.
    SETTINGS_MODULE = None

    def __init__(self, default_settings):
        """
        Requests for configuration variables not in this class are satisfied
        from the module specified in default_settings (if possible).
        """
        self.__dict__['_deleted'] = set()
        self.default_settings = default_settings

    def __getattr__(self, name):
        if name in self._deleted:
            raise AttributeError
        return getattr(self.default_settings, name)

    def __setattr__(self, name, value):
        self._deleted.discard(name)
        if name == 'DEFAULT_CONTENT_TYPE':
            warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
        super().__setattr__(name, value)

    def __delattr__(self, name):
        self._deleted.add(name)
        if hasattr(self, name):
            super().__delattr__(name)

    def __dir__(self):
        return sorted(
            s for s in list(self.__dict__) + dir(self.default_settings)
            if s not in self._deleted
        )

    def is_overridden(self, setting):
        deleted = (setting in self._deleted)
        set_locally = (setting in self.__dict__)
        set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
        return deleted or set_locally or set_on_default

    def __repr__(self):
        return '<%(cls)s>' % {
            'cls': self.__class__.__name__,
        }


settings = LazySettings()

2 个答案:

答案 0 :(得分:1)

我只使用环境变量和包environ

env = environ.Env()
if not env.bool('PRODUCTION', 'False'):
    # Select this PRODUCTTION=False or if not defined 
    DATABASES = 'default': {
        # ...
    }
else:
   DATABASES = 'default': {
       # ...
    }

答案 1 :(得分:0)

这是您使用单独的“设置”目录的方法。小心切换到此选项,因为它最初可能会破坏某些东西,例如您的manage.py文件。

dev.pyprod.py都将从base.py导入内容。开发人员和生产人员所共有的所有内容都可以作为基础。对于开发而言,任何唯一的内容都将进入dev.py,对于生产而言,所有特定的内容都将进入prod.py

.bashrc:

export DJANGO_DEVELOPMENT=true

manage.py

import os

if os.environ['DJANGO_DEVELOPMENT'] == 'true':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.dev")
else:
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings.prod")

目录结构

-> app
--> settings
---> base.py
---> prod.py
---> dev.py

dev.py

from app.settings.base import * 

# This will overwrite anything in base.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mainpage',
        'USER': 'mainpage',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '5432'
    },
}

修改任何使用DJANGO_SETTINGS_MODULE来使用新环境变量的位置,例如wsgi.py

import os

from django.core.wsgi import get_wsgi_application

if os.environ["DJANGO_DEVELOPMENT"]:
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainpage.settings.dev")
else: 
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mainpage.settings.prod")

application = get_wsgi_application()