python教程分享Django加载配置的过程详解

一. django服务启动 manage.py

os.environ.setdefault("django_settings_module", "ui.settings")  设置配置文件环境变量-
#!/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文件中引入配置

from django.conf import settings

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

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方法。

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__方法

    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)

    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加载配置内容请搜索<猴子技术宅>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<猴子技术宅>!

需要了解更多python教程分享Django加载配置的过程详解,都可以关注python教程分享栏目—猴子技术宅(www.ssfiction.com)

本文来自网络收集,不代表猴子技术宅立场,如涉及侵权请点击右边联系管理员删除。

如若转载,请注明出处:https://www.ssfiction.com/pythons/1091948.html

(0)
上一篇 3天前
下一篇 3天前

精彩推荐

发表评论

您的电子邮箱地址不会被公开。