基于django中间件的编程思想

基于django中间件的编程思想

在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',
]

在这种形式的中间件中,当我们注释掉一行字符串时,它对应的中间件无效,当注释打开时,对应的中间件全局生效。

[En]

In this form of middleware, when we comment out a line of string, its corresponding middleware is invalid, and when the comment is opened, the corresponding middleware takes effect globally.

这是怎么回事?

[En]

How does this work?

基于django中间件的编程思想

我们通过下面的一个小案例来了解一下其工作原理:

案例的需求:定义三个功能,三个功能分别是短信发送内容、qq发送内容、邮箱发送内容,把其也写成列表套字符串的形式,当注释掉其中一种功能时,该功能就失效。

基于django中间件的编程思想
第一步:在一个包里面创建三个py文件,分别定义一个对于功能的类
class Email:
    def __init__(self):
        pass

    def send(self,content):
        print('邮箱发送%s'%content)

class Msg:
    def __init__(self):
        pass

    def send(self, content):
        print('信息发送%s' % content)
.....

第二步:创建一个setting.py
CONTENT_LIST = [
    # 'notify.email.Email',
    'notify.msg.Msg',
    'notify.qq.Qq'
]

第三步:在包里面的__init__文件里面,对于setting里面的列表字符串循环,从而得到对于的模块和类名,在函数里循环一次就调用一次对应类里面的方法
import setting
import importlib

def send_all(content):
    for path in setting.CONTENT_LIST: # path 每次循环得到的是'notify.email.Email'的字符串
        module_path,class_name = path.rsplit('.',maxsplit=1) # 从右往左切一个,然后在拆包
        # module_path = 'notify.email'  class_name = 'Email'
        # 1 利用字符串导入模块
        module = importlib.import_module(module_path)  # from notify import email
        # 2 利用反射获取类名
        cls = getattr(module,class_name)  # Email、QQ、Wechat
        # 3 生成类的对象
        obj = cls()
        # 4 利用鸭子类型直接调用send方法
        obj.send(content)

第四步:创建一个start.py文件,用于启动notify文件里的功能
import notify

notify.send_all('快下课了') #去notify的__init__里找对应的函数调用

以后如果需要不用那种功能,只需要注释掉setting里面的字符串就行,这样就真正的解耦合了!!

django的中间件编写思路,其实就类似于上述的操作!

Original: https://www.cnblogs.com/suncolor/p/16607697.html
Author: 等日落
Title: 基于django中间件的编程思想

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/498693/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球