当前位置:   article > 正文

django17:importlib应用中间件代码思想_task_cls = getattr(pkg), cls_name)‘

task_cls = getattr(pkg), cls_name)‘

转载:https://www.cnblogs.com/alice-bj/articles/9276880.html

 

背景

仿django的中间件的编程思想

用户可通过配置,选择是否启用某个组件/某个功能,只需要配置

eg:报警系统,发邮件,发微信 。。。

( 根据字符串导入模块, 利用反射找到模块下的类,实例化。执行 )

 

code

 

  1. # settings.py
  2. NOTIFY_LIST = [
  3. 'notify.email.Email',
  4. 'notify.msg.Msg',
  5. 'notify.wechat.Wechat',
  6. ]
  7. -----------------------------
  8. # app.py
  9. from notify import send_xxx
  10. def run():
  11. send_xxx("报警")
  12. if __name__ == "__main__":
  13. run()
  14. ----------------------------
  15. # notify/__init__.py
  16. # 根据字符串 导入模块
  17. import settings
  18. import importlib
  19. def send_xxx(content):
  20. for path in settings.NOTIFY_LIST:
  21. # 'notify.email.Email',
  22. # 'notify.msg.Msg',
  23. # 'notify.wechat.Wechat',
  24. module_path,class_name = path.rsplit('.',maxsplit=1)
  25. # 根据字符串导入模块
  26. module = importlib.import_module(module_path)
  27. # 根据类名称去模块中获取类
  28. cls = getattr(module,class_name)
  29. # 根据类实例化
  30. obj = cls()
  31. obj.send(content)
  32. -----------------------------
  33. # notify/email.py
  34. class Email(object):
  35. def __init__(self):
  36. pass
  37. def send(self,content):
  38. print("email send..")
  39. # notify/msg.py
  40. class Msg(object):
  41. def __init__(self):
  42. pass
  43. def send(self,content):
  44. print("msg send..")
  45. # notify/wechat.py
  46. class Wechat(object):
  47. def __init__(self):
  48. pass
  49. def send(self,content):
  50. print("wechat send..")

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/524371
推荐阅读
相关标签
  

闽ICP备14008679号