Django读取配置⽂件的机制解析
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.
""" 通过指定的环境变量load设置模块
settings_module = (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 figure() before accessing settings."
% (desc, ENVIRONMENT_VARIABLE))
self._wrapped = Settings(settings_module) #这⾥是_wrapped的初始化 _wraped带有了各种global_settings⾥的属性
.....电脑开机密码忘记了怎么办
韩国娱乐圈种子
.....
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)  #返回从global_settings⾥得到的的属性
雅名self.__dict__[name] = val
return val
192.168 1.1⾸先要了解__getattr__函数的作⽤:
通过实例访问属性,都会经过__getattribute__函数。⽽当属性不存在时,仍然需要访问__getattribute__,不过接着要访问__getattr__。这就好像是⼀个异常处理函数。
当使⽤***类***访问不存在的变量是,不会经过__getattr__函数
这⾥的关键在于,如果我们的配置⽂件有定义⼀个CACHE的变量,我们⼜想在setting是个类的情况下直接使⽤setting.CACHE直接得到这个值,事实上Django不会在LazySettings及其所有⽗类中涉及到变量的初始化,但我们可以通过__getattr__函数的机制来得到这个值,通过import global_setting.py⽂件,在Setting这个类中实现了配置的初始化
f import global_settings
class Settings(object):
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))            #这⾥读取global_settings
# store the settings module in case someone later cares
self.SETTINGS_MODULE = settings_module
读取配置文件失败mod = importlib.import_module(self.SETTINGS_MODULE)  #这⾥读取mysite.settings
...
...
⽽DJANGO_SETTING_MODULE环境变量是让django项⽬主⽂件夹下的settings模块被包含到python可以到的⽬录下,开发情况下不需要(⼀般来说项⽬叫mysite,那么这个值就是mysite.settings)你可以在managy.py中到:
if __name__ == "__main__":
我们通常会在当前⽂件夹运⾏,python可以搜索到。如果需要运⾏在其他服务器上,就必须指定DJANGO_SETTINGS_MODULE变量。django在编译时,先载⼊global_settings.py中的配置,然后加载指定的settings⽂件,重写改变的设定。
如果想写基于Django的软件想配置⾃⼰⼯程特有的设置的话,可以继承⼀个⼦类,在⼦类中重写⼀个_setup⽅法,同时赋值⾃⼰的环境变量和global_settings.py⽂件