在项目中有两套配置文件,一个是默认配置(如rest_framework中的settings),一个是用户配置(Django框架的settings)
需求:
如果用户配置过了某个参数,就用用户配置过的;如果用户没有配置过,就用默认配置中的参数
实现:
1、globalsetting.py
DEBUG = True
2、setting.py
DEBUG = False
3、在conf的__init__中
# 参考Django源码,实现
import importlib
import os
from conf import globalsetting
class Setting:
def __init__(self):
# 从环境标量中取出用户配置
user_setting = os.environ.get('user_setting') # 字符串类型
# print(user_setting) # usersetting.setting
# print(dir(globalsetting))
# 将globalsetting转换为列表
for setting in dir(globalsetting):
if setting.isupper():
# getattr(globalsetting, setting) 获取globalsetting中setting对应的值
# setattr(...) 将获取到的值,赋给Setting对象的setting属性
setattr(self, setting, getattr(globalsetting, setting))
# 将字符串类型的 . 数据,转换为文件路径,mod 即为 setting.py
mod = importlib.import_module(user_setting)
# print(mod)
for setting in dir(mod):
if setting.isupper():
# getattr(mod, setting) 获取mod中setting的值
# setattr(...) 将Setting对象的setting属性设置为获取的值,如果设置过默认的,用户又配置过,就会覆盖掉默认的值
setattr(self, setting, getattr(mod, setting))
settings = Setting()
4、test.py
import os
# 将用户配置文件加到环境变量中
os.environ.setdefault('user_setting', 'usersetting.setting')
from conf import settings
print(settings.DEBUG)
附:django配置文件调用的源码
- 即
__init__.py
"""
Settings and configuration for Django.
Read values from the module specified by the DJANGO_SETTINGS_MODULE environment
variable, and then from django.conf.global_settings; see the global_settings.py
for a list of all possible variables.
"""
import importlib
import os
import time
import warnings
from django.conf import global_settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.deprecation import RemovedInDjango30Warning
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 settings are needed, if the user hasn't
configured 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().__setattr__(name, value)
def __delattr__(self, name):
"""Delete a setting and clear it from cache if needed."""
super().__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):
"""Return True if the settings have already been configured."""
return self._wrapped is not empty
class Settings:
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
mod = importlib.import_module(self.SETTINGS_MODULE)
tuple_settings = (
"INSTALLED_APPS",
"TEMPLATE_DIRS",
"LOCALE_PATHS",
)
self._explicit_settings = set()
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)
if not self.SECRET_KEY:
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
if self.is_overridden('DEFAULT_CONTENT_TYPE'):
warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
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
def __repr__(self):
return '<%(cls)s "%(settings_module)s">' % {
'cls': self.__class__.__name__,
'settings_module': self.SETTINGS_MODULE,
}
class UserSettingsHolder:
"""Holder for user configured settings."""
# SETTINGS_MODULE doesn't make much sense in the manually configured
# (standalone) case.
SETTINGS_MODULE = None
def __init__(self, default_settings):
"""
Requests for configuration variables not in this class are satisfied
from the module specified in default_settings (if possible).
"""
self.__dict__['_deleted'] = set()
self.default_settings = default_settings
def __getattr__(self, name):
if name in self._deleted:
raise AttributeError
return getattr(self.default_settings, name)
def __setattr__(self, name, value):
self._deleted.discard(name)
if name == 'DEFAULT_CONTENT_TYPE':
warnings.warn('The DEFAULT_CONTENT_TYPE setting is deprecated.', RemovedInDjango30Warning)
super().__setattr__(name, value)
def __delattr__(self, name):
self._deleted.add(name)
if hasattr(self, name):
super().__delattr__(name)
def __dir__(self):
return sorted(
s for s in list(self.__dict__) + dir(self.default_settings)
if s not in self._deleted
)
def is_overridden(self, setting):
deleted = (setting in self._deleted)
set_locally = (setting in self.__dict__)
set_on_default = getattr(self.default_settings, 'is_overridden', lambda s: False)(setting)
return deleted or set_locally or set_on_default
def __repr__(self):
return '<%(cls)s>' % {
'cls': self.__class__.__name__,
}
settings = LazySettings()
Django配置文件调用源码分析
在这里global_settings.py
是django默认的配置文件,而我们项目中下的settings.py
是提供给用户的自定义配置文件
在实际开发中通过from django.conf import settings
来导入django的配置文件
-
这句化实则是导入
__init__.py
中的settings
对象,这是一个单例模式的demo,每一次导入配置都是同一个对象
-
settings为一个LazySettings对象
LazySettings对象,就是延迟获取配置内容。比如,我们定义了一个对象A,并对其添加了一些属性,对A初始化时,我们将A的属性的值设置为空,当我们要访问对象A其中的一个属性时,我们才加载属性的值,并将空值设置为对应的值,返回属性值,下次获取属性值时,属性值不为空,直接返回属性值。
-
settings.DEBUG调用setting中的配置
此时响应的是
LazySettings
中的__getattr__
方法,这里的name
参数即DEBUG
-
self._wrapped
的值为empty,由于LazySettings类继承LazyObject类,而LazySettings类中没有_wrapped
属性,由父类决定。因此进入if中,执行self._setup(name)
,即self._setup('DEBUG')
-
执行
self._setup(name)
-
首先从环境变量中获取key为
DJANGO_SETTINGS_MODULE
的值 (这个值是在我们项目的manage.py
中设置进环境变量),获取结果实则是实际项目中的自定义配置文件,结合manag.py
这里settings_module
=SeMF.settings
-
再到
self._wrapped=Settings(settings_module)
创建一个Settings对象
manage.py,在项目启动时,想将配置文件添加到环境变量中
-
-
-
创建
Settings
对象先遍历默认配置中的变量,并将变量的值赋值给
Settings
对象中对应的属性;然后在遍历用户自定义配置,重新给Settings
对象的属性赋值。因此,如果自定义配置文件中存在默认配置中的变量,就会覆盖Settings
对象的对应属性的值setattr(obj, obj_attr, attr_value)
-
这里的
setting_module
是 用户自定义的配置文件,global_settings
是django模块中默认的配置文件-
从 默认配置文件 中的循环所有变量、方法,(配置文件中属性均为大写),并将对应的值
Settings
对象中对应的属性 -
导入用户自定义配置文件,
for
循环获取 自定义配置文件 中所有的变量、方法,并赋值给Settings
对象中对应的属性。self._explicit_settings.add(setting)
将每一个自定义配置中大写的变量全都添加到_explicit_settings
集合中,只是用于后续的if判断条件。
-
-
-
Settings
对象创建完成,回到LazySettings中的__getattr__
中,执行val = getattr(self._wrapped, name)
,这里self._wrapped
是Settings
对象。从Settings对象中取出对应属性name
,并将值放入LazySettings对象的名称空间中,并返回值