轉載: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..")
?