zoukankan      html  css  js  c++  java
  • importlib应用

    背景

    仿django的中间件的编程思想

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

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

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

    code

    # settings.py
    
    NOTIFY_LIST = [
        'notify.email.Email',
        'notify.msg.Msg',
        'notify.wechat.Wechat',
    ]
    
    -----------------------------
    
    # app.py
    
    from notify import send_xxx
    
    def run():
        send_xxx("报警")
    
    if __name__ == "__main__":
        run()
    
    ----------------------------
    
    # notify/__init__.py
    
    # 根据字符串 导入模块
    
    import settings
    import importlib
    
    def 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.py
    
    class Email(object):
        def __init__(self):
            pass
    
        def send(self,content):
            print("email send..")
    
    
    # notify/msg.py
    
    class Msg(object):
        def __init__(self):
            pass
    
        def send(self,content):
            print("msg send..")
    
    # notify/wechat.py class Wechat(object): def __init__(self): pass def send(self,content): print("wechat send..")
  • 相关阅读:
    redis主从架构
    redis持久化
    git 首次push失败
    Java8 CompletableFuture
    Mac Item2自动远程连接服务器
    Java8 日期和时间类
    【LeetCode】31. 下一个排列
    【LeetCode】30. 串联所有单词的子串
    【LeetCode】29. 两数相除
    【LeetCode】28. 实现 strStr()
  • 原文地址:https://www.cnblogs.com/alice-bj/p/9276880.html
Copyright © 2011-2022 走看看