写在开头:
每个APP都会有配置文件,像下代码Django等等这种的settings里面的配置导入都是字符串的,他们是怎么做的呢?
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
1.首先假如有这种结构:
2.开始
csrf中有这么一个类:
# Author:Jesi
# Time : 2018/10/19 12:33
class CORS(object):
def process_response(self):
print(666)
想要在run中导入csrf这个文件怎么做呢?
# Author:Jesi
# Time : 2018/10/19 12:48
path="auth.csrf.CORS" import importlib #导入这个模块 module_path,class_name=path.rsplit(".",maxsplit=1) #通过右边的.分割开。 print(module_path,class_name) #auth.csrf CORS
#根据字符串的形式导入模块
m=importlib.import_module(module_path) #然后根据这个方法可以导入模块 cls = getattr(m,class_name) #通过getattr拿到这个类。
obj=cls() #实例化对象
obj.process_response() #执行打印666
3.源码
Django的配置文件就是这么导入的:
附上源码:
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
"""
try:
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError as err:
raise ImportError("%s doesn't look like a module path" % dotted_path) from err module = import_module(module_path) try:
return getattr(module, class_name)
except AttributeError as err:
raise ImportError('Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
) from err