脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Django加载配置的过程详解

Django加载配置的过程详解

2022-12-30 15:10托塔天王李 Python

这篇文章主要介绍了Django加载配置的过程详解,包括Django服务启动 manage.py的详细介绍,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

一. Django服务启动 manage.py

?
1
2
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ui.settings")
设置配置文件环境变量-
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ui.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError:
        # The above import may fail for some other reason. Ensure that the
        # issue is really that Django is missing to avoid masking other
        # exceptions on Python 2.
        try:
            import django
        except ImportError:
            raise ImportError(
                "Couldn't import Django. Are you sure it's installed and "
                "available on your PYTHONPATH environment variable? Did you "
                "forget to activate a virtual environment?"
            )
        raise
    execute_from_command_line(sys.argv)

二. 引入配置

django/core/management/init.py文件中引入配置

?
1
from django.conf import settings

django/conf/init.py配置文件源码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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 we need any settings at all, if the user has not
        previously configured the 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(LazySettings, self).__setattr__(name, value)
    def __delattr__(self, name):
        """
        Delete a setting and clear it from cache if needed.
        """
        super(LazySettings, self).__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):
        """
        Returns True if the settings have already been configured.
        """
        return self._wrapped is not empty
settings = LazySettings() # 单例模式

LazySettings()惰性加载是一种延迟计算的技术,当只有真正需要使用结果的时候才会去计算。Django提供了两种惰性加载模块,分别是lazy和LazyObject,前者主要针对可以调用的对象,延迟函数的调用;后者针对类,延迟类的实例化。

如果想要让某个类有延迟实例化的功能,必须做两件事情:

1)继承LazyObject;
2)实现_setup方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
empty = object()
def new_method_proxy(func):
    def inner(self, *args):
        if self._wrapped is empty:
            self._setup()
        return func(self._wrapped, *args)
    return inner
class LazyObject(object):
    """
    A wrapper for another class that can be used to delay instantiation of the
    wrapped class.
    By subclassing, you have the opportunity to intercept and alter the
    instantiation. If you don't need to do that, use SimpleLazyObject.
    """
    # Avoid infinite recursion when tracing __init__ (#19456).
    _wrapped = None
    def __init__(self):
        """
        初始化
        """
        # Note: if a subclass overrides __init__(), it will likely need to
        # override __copy__() and __deepcopy__() as well.
        self._wrapped = empty
    __getattr__ = new_method_proxy(getattr)
    def __setattr__(self, name, value):
        if name == "_wrapped":
            # Assign to __dict__ to avoid infinite __setattr__ loops.
            self.__dict__["_wrapped"] = value
        else:
            if self._wrapped is empty:
                self._setup()
            setattr(self._wrapped, name, value)
    def __delattr__(self, name):
        if name == "_wrapped":
            raise TypeError("can't delete _wrapped.")
        if self._wrapped is empty:
            self._setup()
        delattr(self._wrapped, name)
    def _setup(self):
        """
        Must be implemented by subclasses to initialize the wrapped object.
        """
        raise NotImplementedError('subclasses of LazyObject must provide a _setup() method')
    def __reduce__(self):
        if self._wrapped is empty:
            self._setup()
        return (unpickle_lazyobject, (self._wrapped,))
    def __getstate__(self):
        if self._wrapped is empty:
            self._setup()
        return self._wrapped.__dict__

三. 加载配置

ManagementUtility 的execute方法的 settings.INSTALLED_APPS

1) settings.INSTALLED_APPS 因为settings没有INSTALLED_APPS属性就会调用LazySettings的__getattr__方法

?
1
2
3
4
5
6
7
8
9
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

2)self._wrapped is empty(empty是LazyObject的类属性)为True, 就会执行LazySettings的_setup方法,实例self._wrapped =Settings(settings_module)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def _setup(self, name=None):
    """
    Load the settings module pointed to by the environment variable. This
    is used the first time we need any settings at all, if the user has not
    previously configured the 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)

3) 后面再访问属性时直接从self._wrapped.dict(settings.wrapped.dict)中获取

到此这篇关于Django加载配置的过程详解的文章就介绍到这了,更多相关django加载配置内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_40861391/article/details/124714710

延伸 · 阅读

精彩推荐
  • Python关于Pycharm无法debug问题的总结

    关于Pycharm无法debug问题的总结

    今天小编就为大家分享一篇关于Pycharm无法debug问题的总结,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...

    章小幽6232021-05-18
  • Pythonpython 图片去噪的方法示例

    python 图片去噪的方法示例

    这篇文章主要介绍了python 图片去噪的方法示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随...

    418951905152021-08-06
  • PythonPyTorch学习:动态图和静态图的例子

    PyTorch学习:动态图和静态图的例子

    今天小编就为大家分享一篇PyTorch学习:动态图和静态图的例子,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    有点方5822020-05-07
  • PythonPython List remove()实例用法详解

    Python List remove()实例用法详解

    在本篇内容里小编给大家整理了一篇关于Python List remove()方法及实例,有需要的朋友们跟着学习下。 ...

    脚本之家6342021-12-16
  • PythonPython UnboundLocalError和NameError错误根源案例解析

    Python UnboundLocalError和NameError错误根源案例解析

    这篇文章主要介绍了Python UnboundLocalError和NameError错误根源解析,本文通过案例分析实例代码相结合的形式给大家介绍的非常详细,具有一定的参考借鉴价值...

    alpha_panda12112021-04-14
  • Python通过Python中的CGI接口讲解什么是WSGI

    通过Python中的CGI接口讲解什么是WSGI

    这篇文章主要为大家通过Python中的CGI接口及应用示例讲解什么是WSGI,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪...

    Biiigfish5412022-12-04
  • Pythonpython实现Flappy Bird源码

    python实现Flappy Bird源码

    这篇文章主要为大家详细介绍了python实现Flappy Bird源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    mini猿要成长QAQ9912021-05-07
  • PythonPython性能提升之延迟初始化

    Python性能提升之延迟初始化

    本文给大家分享的是在Python中使用延迟计算来提升性能的方法,非常的实用,有需要的小伙伴可以参考下...

    脚本之家2052020-09-13