Django中的module的加载是通过反射来完成的,借助importlib中的import_module函数来实现的动态加载。import_module的内部通过使用了递归和线程锁,字符串的切割,实现模块的加载。

主要有以下几个步骤:

根据字符串的形式导入模块

假设在有以下的类跟方法:


path = "handler.basic.BaseHandler"


func_name = "process_request"

导入目标函数:

import importlib

# 通过切割拿到模块和类名
module_path,cls_name = path.rsplit('.', 1)
# 导入模块
module = importlib.import_module(module_path)
print(module)

去模块中找到相应的类

通过反射拿到类。

cls =  getattr(module, cls)

根据相应的类实例化

实例化对象:

obj = cls()

执行对象方法

通过反射拿到方法,

func = getattr(obj, func_name)
fuc()

Django中间件源码

    def load_middleware(self):
"""
Populate middleware lists from settings.MIDDLEWARE (or the deprecated
MIDDLEWARE_CLASSES). Must be called after the environment is fixed (see __call__ in subclasses).
"""
self._request_middleware = []
self._view_middleware = []
self._template_response_middleware = []
self._response_middleware = []
self._exception_middleware = [] if settings.MIDDLEWARE is None:
warnings.warn(
"Old-style middleware using settings.MIDDLEWARE_CLASSES is "
"deprecated. Update your middleware and use settings.MIDDLEWARE "
"instead.", RemovedInDjango20Warning
)
handler = convert_exception_to_response(self._legacy_get_response)
for middleware_path in settings.MIDDLEWARE_CLASSES:
mw_class = import_string(middleware_path)
try:
mw_instance = mw_class()
except MiddlewareNotUsed as exc:
if settings.DEBUG:
if six.text_type(exc):
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
else:
logger.debug('MiddlewareNotUsed: %r', middleware_path)
continue if hasattr(mw_instance, 'process_request'):
self._request_middleware.append(mw_instance.process_request)
if hasattr(mw_instance, 'process_view'):
self._view_middleware.append(mw_instance.process_view)
if hasattr(mw_instance, 'process_template_response'):
self._template_response_middleware.insert(0, mw_instance.process_template_response)
if hasattr(mw_instance, 'process_response'):
self._response_middleware.insert(0, mw_instance.process_response)
if hasattr(mw_instance, 'process_exception'):
self._exception_middleware.insert(0, mw_instance.process_exception)
else:
handler = convert_exception_to_response(self._get_response)
for middleware_path in reversed(settings.MIDDLEWARE):
# 从setting中的中间件的配置,切割拿到导入的模块和类名,通过反射拿到对应的类
middleware = import_string(middleware_path)
try:
# 中间件实例化对象,
mw_instance = middleware(handler)
except MiddlewareNotUsed as exc:
if settings.DEBUG:
if six.text_type(exc):
logger.debug('MiddlewareNotUsed(%r): %s', middleware_path, exc)
else:
logger.debug('MiddlewareNotUsed: %r', middleware_path)
continue if mw_instance is None:
raise ImproperlyConfigured(
'Middleware factory %s returned None.' % middleware_path
) if hasattr(mw_instance, 'process_view'):
self._view_middleware.insert(0, mw_instance.process_view)
if hasattr(mw_instance, 'process_template_response'):
self._template_response_middleware.append(mw_instance.process_template_response)
if hasattr(mw_instance, 'process_exception'):
self._exception_middleware.append(mw_instance.process_exception) handler = convert_exception_to_response(mw_instance) # We only assign to this when initialization is complete as it is used
# as a flag for initialization being complete.
self._middleware_chain = handler ############################################################################## 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: django.middleware.csrf
# class_name: CsrfViewMiddleware
module_path, class_name = dotted_path.rsplit('.', 1)
except ValueError:
msg = "%s doesn't look like a module path" % dotted_path
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) # module_path: django.middleware.csrf
# 通过module_path导入模块
module = import_module(module_path) try:
# 拿到当前类的类名
return getattr(module, class_name)
except AttributeError:
msg = 'Module "%s" does not define a "%s" attribute/class' % (
module_path, class_name)
six.reraise(ImportError, ImportError(msg), sys.exc_info()[2]) ##################################################################### def import_module(name, package=None):
"""Import a module. The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import. """
level = 0
if name.startswith('.'):
if not package:
msg = ("the 'package' argument is required to perform a relative "
"import for {!r}")
raise TypeError(msg.format(name))
for character in name:
if character != '.':
break
level += 1
# _gcd_import中使用了递归和线程锁,字符串的切割,实现模块的加载。
return _bootstrap._gcd_import(name[level:], package, level)

Django中模块的加载原理的更多相关文章

  1. django中的懒加载机制

    懒加载在前端中的意义: 懒加载的主要目的就是作为服务器前端的优化,减少请求次数或者延迟请求数. 实现原理: 先加载一部分数据,当触发某个条件时利用异步加载剩余的数据,新得到的数据不会影响原有数据的显示 ...

  2. 深入理解 Laravel 中 config 配置加载原理

    Laravel的配置加载其实就是加载config目录下所有文件配置.如何过使用php artisan config:cache则会把加载的配置合并到一个配置文件中,下次请求就不会再去加载config目 ...

  3. Django中的图片加载不出来解决方式记录

    背景:Python3.6 + Django2.2 在模板中的html文件中引用图片时,在浏览器中图片总是显示不出来,上网查了很多解决方式,但是都没有解决问题,最终尝试了多次后得以解决,但不清楚原理: ...

  4. Grunt-cli的执行过程以及Grunt加载原理

    通过本篇你可以了解到: 1 grunt-cli的执行原理 2 nodeJS中模块的加载过程 Grunt-cli原理 grunt-cli其实也是Node模块,它可以帮助我们在控制台中直接运行grunt命 ...

  5. node 中第三方模块的加载过程原理

    node 中第三方模块的加载过程原理 凡是第三方模块都必须通过 npm 来下载 使用的时候就可以通过require('包名') 的方式来进行加载才可以使用 不可能有任何一个第三方包和核心模块的名字是一 ...

  6. AMD-require.js模块加载原理

    项目中使用大了require.js,功能实现,现重新学习下模块加载原理相关知识,借鉴如下博文:https://blog.csdn.net/ai52011/article/details/7711361 ...

  7. Node.js require 模块加载原理 All In One

    Node.js require 模块加载原理 All In One require 加载模块,搜索路径 "use strict"; /** * * @author xgqfrms ...

  8. JS模块加载器加载原理是怎么样的?

    路人一: 原理一:id即路径 原则.通常我们的入口是这样的: require( [ 'a', 'b' ], callback ) .这里的 'a'.'b' 都是 ModuleId.通过 id 和路径的 ...

  9. js中的预加载与懒加载(延迟加载)

    js中加载分两种:预加载与延迟加载 一.  预加载,增强用户的体验,但会加载服务器的负担.一般会使用多种 CSS(background).JS(Image).HTML(<img />) . ...

随机推荐

  1. 路飞学城Python-Day53

    01-jquery的介绍 JS在做项目或者是实现功能的时候,用JS去操作DOM元素非常复杂,代码量大,重复性代码也多 多个元素使用for循环遍历也是非常麻烦的,对于JS使用来说加大了难度 jQuery ...

  2. flex笔记 - 基础

    flex笔记 - 基础 文章中的所有图示代码都放在了github上: 阮一峰flex博客跟学代码 传统的布局解决方案,基于盒模型, 依赖 display, position, float属性来进行布局 ...

  3. 用chrony代替ntpd时间同步服务器

    Chrony是一个开源的自由软件,它能保持系统时钟与时钟服务器(NTP)同步,让时间保持精确. 它由两个程序组成:chronyd和chronyc. chronyd是一个后台运行的守护进程,用于调整内核 ...

  4. 接口(interface) 可以 new()吗???~

    比如 一个接口 A ,里面有一个方法fun1(),一般我们是先定义它的实现再引用它,比如 public class ImpA implements A{ public void fun1(){ //d ...

  5. [Angular] Service Worker Version Management

    If our PWA application has a new version including some fixes and new features. By default, when you ...

  6. [HTML 5] Atomic Relevant Busy

    Together 'aria-live', we can use 'aria-atomic', 'aria-relevant' and 'aria-busy' to give more informa ...

  7. 《SAS编程与数据挖掘商业案例》学习笔记之十五

    继续<SAS编程与数据挖掘商业案例>读书笔记,本次重点:输出控制 主要内容包含:log窗体输出控制.output窗体输出控制.ods输出控制 1.log窗体输出控制 将日志输出到外部文件 ...

  8. 【jQuery】对于复选框操作的attr与prop

    这个是在jQuery1.6版本号之后出现的鬼东西.受影响的主要有下拉列表select与复选框checkbox.众所周知.在jQuery中能够用attr()取出节点的属性,然而对于checkbox却不是 ...

  9. JavaScript 获取小数任一小数点后的位数的小数

    用Javascript取float型小数点后两位,例22.127456取成22.13,怎样做? 1.这样的方法最不推荐: function get(){ var s = 22.127456 + &qu ...

  10. 关于App class loader的总结

    关于App class loader的总结 2010-05-11 15:19:09 分类: 系统运维 Java本身是一种设计的非常简单,非常精巧的语言,所以Java背后的原理也很简单,归结起来就是两点 ...