importcopyimportosimportsysfromimportlibimportimport_modulefromimportlib.utilimportfind_specasimportlib_finddefcached_import(module_path,class_name):# Check whether module is loaded and fully initialized.ifnot((module:=sys.modules.get(module_path))and(spec:=getattr(module,"__spec__",None))andgetattr(spec,"_initializing",False)isFalse):module=import_module(module_path)returngetattr(module,class_name)
[docs]defimport_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)exceptValueErroraserr:raiseImportError("%s doesn't look like a module path"%dotted_path)fromerrtry:returncached_import(module_path,class_name)exceptAttributeErroraserr:raiseImportError('Module "%s" does not define a "%s" attribute/class'%(module_path,class_name))fromerr
defautodiscover_modules(*args,**kwargs):""" Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to access it. """fromgingerdj.appsimportappsregister_to=kwargs.get("register_to")forapp_configinapps.get_app_configs():formodule_to_searchinargs:# Attempt to import the app's module.try:ifregister_to:before_import_registry=copy.copy(register_to._registry)import_module("%s.%s"%(app_config.name,module_to_search))exceptException:# Reset the registry to the state before the last import# as this import will have to reoccur on the next request and# this could raise NotRegistered and AlreadyRegistered# exceptions (see #8245).ifregister_to:register_to._registry=before_import_registry# Decide whether to bubble up this error. If the app just# doesn't have the module in question, we can ignore the error# attempting to import it, otherwise we want it to bubble up.ifmodule_has_submodule(app_config.module,module_to_search):raisedefmodule_has_submodule(package,module_name):"""See if 'module' is in 'package'."""try:package_name=package.__name__package_path=package.__path__exceptAttributeError:# package isn't a package.returnFalsefull_module_name=package_name+"."+module_nametry:returnimportlib_find(full_module_name,package_path)isnotNoneexceptModuleNotFoundError:# When module_name is an invalid dotted path, Python raises# ModuleNotFoundError.returnFalsedefmodule_dir(module):""" Find the name of the directory that contains a module, if possible. Raise ValueError otherwise, e.g. for namespace packages that are split over several directories. """# Convert to list because __path__ may not support indexing.paths=list(getattr(module,"__path__",[]))iflen(paths)==1:returnpaths[0]else:filename=getattr(module,"__file__",None)iffilenameisnotNone:returnos.path.dirname(filename)raiseValueError("Cannot determine directory containing %s"%module)