转载:https://www.cnblogs.com/alice-bj/articles/9276880.html
背景
仿django的中间件的编程思想
用户可通过配置,选择是否启用某个组件/某个功能,只需要配置
eg:报警系统,发邮件,发微信 。。。
( 根据字符串导入模块, 利用反射找到模块下的类,实例化。执行 )
code
# settings.pyNOTIFY_LIST = ['notify.email.Email','notify.msg.Msg','notify.wechat.Wechat',
]-----------------------------# app.pyfrom notify import send_xxxdef run():send_xxx("报警")if __name__ == "__main__":run()----------------------------# notify/__init__.py# 根据字符串 导入模块import settings
import importlibdef send_xxx(content):for path in settings.NOTIFY_LIST:# 'notify.email.Email',# 'notify.msg.Msg',# 'notify.wechat.Wechat',module_path,class_name = path.rsplit('.',maxsplit=1)# 根据字符串导入模块module = importlib.import_module(module_path)# 根据类名称去模块中获取类cls = getattr(module,class_name)# 根据类实例化obj = cls()obj.send(content)-----------------------------# notify/email.pyclass Email(object):def __init__(self):passdef send(self,content):print("email send..")# notify/msg.pyclass Msg(object):def __init__(self):passdef send(self,content):print("msg send..")# notify/wechat.pyclass Wechat(object):def __init__(self):passdef send(self,content):print("wechat send..")