基于Django中间件学习编程思想

正常思路

def wechat(content):
    print('微信通知:%s'%content)


def qq(content):
    print('qq通知:%s'%content)


def email(content):
    print('邮箱通知:%s'%content)

  启动文件

from notify import *


def send_all(content):
    wechat(content)
    qq(content)
    email(content)

if __name__ == '__main__':
    send_all('啥时候放长假')

  这样不利于代码强健性,不利于后期扩展

编程思想

  功能封装成不同的类

class Email(object):
    def __init__(self):
        pass  # 发送邮箱需要做的前期准备工作

    def send(self, content):
        print('邮箱通知:%s' % content)

   创建配置文件

NOTIFY_LIST = [
    'notify.email.Email',
    'notify.qq.QQ',
    'notify.wechat.Wechat',
    # 'notify.msg.Msg',

  创建启动文件

import notify

notify.send_all('有新的消息')

  notify包中__init__.py文件

import settings
import importlib


def send_all(content):
    for path_str in settings.NOTIFY_LIST:  #'notify.email.Email'
        module_path,class_name = path_str.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)

  之后再有新的功能,直接创建该功能的类,并且在配置文件中添加即可,需要删除不需要的功能直接在配置文件中注释就可以。增加了代码的扩展性。

posted @ 2022-03-15 15:57  那就凑个整吧  阅读(24)  评论(0编辑  收藏  举报