插拔式设计

中间件配置

实现功能的插拔式设计,参考django 中间件, 参考django restframework

img

# conf.settings.py
"""
@author RansySun
@create 2019-10-31-21:06
"""
NOTIFY_LIST = [
    'notify.email.Email',
    # 'notify.msg.Msg',
    'notify.wechat.WeChat',
    'notify.qq.QQ',
]

# notify 
# __init__.py
from conf import settings
import importlib
def send_all(content):
    for module_path in settings.NOTIFY_LIST:
        # module = 'notify.email' class_name='Email
        module, class_name = module_path.rsplit('.', maxsplit=1)

        # mod就是模块名
        mod = importlib.import_module(module)

        # 利用反射获取模块中的变量名, 获取类地址
        clas = getattr(mod, class_name)
        obj_class = clas()

        # 使用多态
        obj_class.send_msg(content)
        # print(clas)
# email.py
class Email(object):
    def __init__(self):
        # 发送邮件准备工作
        ...

    def send_msg(self, content):
        print(f'邮件通知:{content}')
        
# Msg.py
class Msg(object):
    def __init__(self):
        # 发送短信准备工作
        ...

    def send_msg(self, content):
        print(f'短信通知:{content}')
        
# QQ.py        
class QQ(object):
    def __init__(self):
        # 发送QQ准备工作
        ...

    def send_msg(self, content):
        print(f'QQ通知:{content}')
# WeChat.py 
class WeChat(object):
    def __init__(self):
        # 发送微信准备工作
        ...

    def send_msg(self, content):
        print(f'微信通知:{content}')
import notify
if __name__ == '__main__':
    notify.send_all('明天周五了')

img

进行统一发送消息,当不需要送则在settings中注释掉就可以,方便管理,既可以插也可以拔!

posted @ 2019-10-31 21:40  RandySun  阅读(587)  评论(0编辑  收藏  举报