每一個APP都會有配置文件,像下代碼Django等等這種的settings裏面的配置導入都是字符串的,他們是怎麼作的呢?django
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', ]
csrf中有這麼一個類:session
# Author:Jesi # Time : 2018/10/19 12:33 class CORS(object): def process_response(self): print(666)
想要在run中導入csrf這個文件怎麼作呢?spa
# 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
Django的配置文件就是這麼導入的:code
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