1. 程式人生 > >Django中settings配置檔案原始碼分析

Django中settings配置檔案原始碼分析

一:使用

在django中使用配置檔案:

# 建議從conf中匯入配置檔案 而非直接匯入該專案的配置檔案
from django.conf import settings

 

二:原始碼分析

conf中的配置檔案涵蓋django的所有配置引數,專案的配置檔案是給使用者進行配置的。匯入conf中的settings,在使用相關配置引數時會先去使用者配置的settings中進行查詢,找不到再去conf中的setting找,詳情見如下原始碼分析:

# 生成LazyObject一個物件  初始化屬性self._wrapped = empty
settings = LazySettings()

# 當settings使用點號查詢屬性時 會響應到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 #呼叫_setup(self, name=要查詢的屬性) 方法 將要查詢的屬性傳入 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檔案取出來 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)) #例項化Setting類,將使用者的配置傳入 self._wrapped = Settings(settings_module) #Setting的__init__方法 def __init__(self, settings_module): # update this dict from global settings (but only for ALL_CAPS settings) # global_settings就是django conf檔案中的配置檔案 dir()方法生成一個列表,其中的引數時該配置檔案的所有變數名 for setting in dir(global_settings): if setting.isupper(): # 使用setattr為物件設值 setattr(self, setting, getattr(global_settings, setting)) # store the settings module in case someone later cares self.SETTINGS_MODULE = settings_module # import_module方法 拿到使用者配置settings.py這個檔案 mod = importlib.import_module(self.SETTINGS_MODULE) tuple_settings = ( "INSTALLED_APPS", "TEMPLATE_DIRS", "LOCALE_PATHS", ) self._explicit_settings = set() # 迴圈使用者配置檔案 如果和conf中配置檔案的key相同那麼就會覆蓋原先設值的值。for迴圈完成,setting物件設值完成,裡面包含使用者的配置引數和conf中的配置引數 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)