importlib应用 - django

背景

仿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..")
posted @ 2018-07-07 11:58  Alice的小屋  阅读(249)  评论(0编辑  收藏  举报