Django源码分析(番外篇)-settings加载

阅读量:115, 115

我们在创建Django项目后,都会有一个settings文件,里面包含着各种配置。 但是我们在项目中使用时配置时,会用from django.conf import settings,这是为什么呢?

懒加载机制

配置文件上可能会用到其他模块,那么就有可能导致循环引用。django采用了懒加载机制。

class LazySettings(LazyObject):
    def _setup(self, name=None):
        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 __getattr__(self, name):
        if self._wrapped is empty:
            self._setup(name)
        val = getattr(self._wrapped, name)
        self.__dict__[name] = val
        return val

懒加载就是使用到的时候再加载。django使用LazyObject代理类实现懒加载。当获取属性时,才会加载_setup()函数。

代码分析

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))

        # 根据DJANGO_SETTINGS_MODULE环境变量,来实例化settings对象
        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':
            # 如果属性是_wrapped,说明要加载不同的settings,这时清空缓存
            # 因为settings变了,之前做的缓存就没有意义了
            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__)).
        """
        # 如果设置过settings,报错
        if self._wrapped is not empty:
            raise RuntimeError('Settings already configured.')

        # 默认根据global_settings实例化UserSettingsHolder
        # 从后面可以看到,这里的holder其实就是代理
        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

LazySettings是一个LazyObject对象,其实是settings对象的代理. settings对象保存在它的_wrapped对象中.

有两种方法设置_wrapped对象: 法一: 设置DJANGO_SETTINGS_MODULE,这是我们经常使用的方法,可以在manage.py中看到它的身影.

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "demo.settings")

法二: 有些情况下,不好使用第一种方法。 如你写的脚本中使用了django的orm,这时,可以使用settings.configure()实现类似的效果

接着往下看:

class Settings:
    def __init__(self, settings_module):
        # update this dict from global settings (but only for ALL_CAPS settings)
        # 从global_settings中导入django默认配置,对应的文件django/conf/global_settings.py
        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
        # 环境变量DJANGO_SETTINGS_MODULE指向的配置文件
        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 = '/usr/share/zoneinfo'
            if (os.path.exists(zoneinfo_root) and not
                    os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
                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,
        }

settings从django/conf/global_settings.py中读取django默认配置, 然后从环境变量DJANGO_SETTINGS_MODULE中读取用户配置. 两者合并起来,才是所有的配置。 到这里,我们就明白了,为什么要从django.conf import settings.

接着看UserSettingsHolder的实现:

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__,
        }

UserSettingsHolder类和Settings类差不多,都实现了Django配置的加载功能。 区别是加载配置的方法不同 UserSettingsHolder是根据传入的default_settings来加载 相同的是default_settings的默认值都是django/conf/global_settings.py. 同时根据用户传入的自定义的配置来存储项目的配置.

settings = LazySettings()

settings是惰性对象,只有在实际使用时才会加载对应的配置

小结

目前为止,基本了解了settings加载的逻辑。 想要让配置生效,要么设置环境变量DJANGO_SETTINGS_MODULE,要么使用settings.configure 配置文件不需要去设置所有项目,因为Django已经默认设置好了,默认的设置在django/conf/global_settings.py

参考: 1.https://docs.djangoproject.com/en/2.0/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage 2.https://www.hongweipeng.com/index.php/archives/1370/

django源码

Django源码分析(番外篇)-settings加载 - 有0条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注

公告

这里是我的博客,欢迎骚扰

近期评论

  • jason发表了 23333333333333333
  • fffffffffffff发表了 444444444444444444

近期评论

  • jason发表了 23333333333333333
  • fffffffffffff发表了 444444444444444444