1. setting.py文件
我们在django项目中,新建一个app的时候,都会有一个setting.py文件,里面包含了整个项目所有的配置,包括apps,中间键,数据库等等,django是如何将该setting文件利用起来的呢。
2. 从setting.py配置文件到Setting类
(1)启动的时候,指定默认的配置文件
django在启动的时候,会调用manage.py文件运行server的实例,在文件一开始的时候,manage.py会调用下面代码
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djtest.settings")
设置默认的配置文件的环境变量DJANGO_SETTINGS_MODULE,该环境变量的名称,定义在django/conf/_init.py文件里面
ENVIRONMENT_VARIABLE = "DJANGO_SETTINGS_MODULE"
(2)根据配置文件里面的配置项,提取到django/conf/_init.py里面的Setting类里面
过程主要包含两步
1. 根据DJANGO_SETTINGS_MODULE指定的配置文件调用mod = importlib.import_module(self.SETTINGS_MODULE),将该模块import
2. 调用for setting in dir(mod) 遍历该mod的属性,将所有的大写的配置属性,提出取来,利用setattr(self, setting, setting_value),保存为自己的属性。
class Settings(BaseSettings): 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 try: # 根据 manage.py 中的os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djtest.settings"),设置的配置文件,import该配置文件 mod = importlib.import_module(self.SETTINGS_MODULE) except ImportError as e: raise ImportError( "Could not import settings '%s' (Is it on sys.path? Is there an import error in the settings file?): %s" % (self.SETTINGS_MODULE, e) ) tuple_settings = ("INSTALLED_APPS", "TEMPLATE_DIRS") # setting文件里面显示申明的属性集合,是个set类型的,是个集合 self._explicit_settings = set() # dir(object)返回object的属性方法列表,因此,这里dir会返回setting文件里面的所有等号左边的属性 for setting in dir(mod): if setting.isupper(): setting_value = getattr(mod, setting) if (setting in tuple_settings and isinstance(setting_value, six.string_types)): raise ImproperlyConfigured("The %s setting must be a tuple. " "Please fix your settings." % setting) # 将setting文件里面的所有属性提出来,放到这个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 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
(3)django的其他模块在使用配置文件里面的配置项的时候,就是从Setting类中获取,而不从配置文件直接获取。