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. vim利器:vundle 管理器和NERDTree插件

    vundle 和nerdtree vundle git: https://github.com/VundleVim/Vundle.vim.git nerdtree git : https://gith ...

  2. 原生js模拟双色球

    <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title> ...

  3. 使用 Laravel 5.5+ 更好的来实现 404 响应

    译文首发于 使用 Laravel 5.5+ 更好的来实现 404 响应,转载请注明出处! Laravel 5.5.10 封装了两个有用的路由器方法,可以帮助我们为用户提供更好的 404 页面.现在,当 ...

  4. NOIP2018提高组省一冲奖班模测训练(五)

    NOIP2018提高组省一冲奖班模测训练(五) http://www.51nod.com/Contest/ContestDescription.html#!#contestId=79 今天有点浪…… ...

  5. php 文件夹 与 文件目录操作

    php文件夹操作函数 string basename ( string path [, string suffix] )给出一个包含有指向一个文件的全路径的字符串,本函数返回基本的文件名.如果文件名是 ...

  6. 数据可视化利器pyechart和matplotlib比较

    python中用作数据可视化的工具有多种,其中matplotlib最为基础.故在工具选择上,图形美观之外,操作方便即上乘. 本文着重说明常见图表用基础版matplotlib和改良版pyecharts作 ...

  7. xcodeproj cannot be opened because the project file cannot be parsed.

    解决方法:    1.对.xcodeproj文件右键,显示包内容 2.双击打开 project.pbxproj 文件 3.找到以上类似的冲突信息(能够用commad + f搜索) 4.删除<&l ...

  8. Linux环境thinkphp配置以及数据源驱动改动

    项目中须要用到thinkphp,以下简称tp. linux版本号:64位CentOS 6.4 Nginx版本号:nginx1.8.0 php版本号:php5.5.28 thinkphp版:3.2.3 ...

  9. [ACM] FZU 1686 神龙的难题 (DLX 反复覆盖)

    Problem 1686 神龙的难题 Accept: 444    Submit: 1365 Time Limit: 1000 mSec    Memory Limit : 32768 KB  Pro ...

  10. 移除apsx视图引擎,及View目录下的web.config的作用

    <> 使用Rezor视图引擎的时候移除apsx视图引擎 Global.asax文件 using System; using System.Collections.Generic; usin ...