django17:importlib应用中间件代码思想
生活随笔
收集整理的這篇文章主要介紹了
django17:importlib应用中间件代码思想
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
轉載: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..")?
總結
以上是生活随笔為你收集整理的django17:importlib应用中间件代码思想的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django16: csrf跨站请求伪造
- 下一篇: django18:auth模块