settings插拔式源码

创建一个文件夹notify

__init__.py

复制代码
import settings
import importlib


def send_all(content):
    for path_str in settings.NOTIFY_LIST:  # 1.拿出一个个的字符串   'notify.email.Email'
        module_path,class_name = path_str.rsplit('.',maxsplit=1)  # 2.从右边开始 按照点切一个 ['notify.email','Email']
        module = importlib.import_module(module_path)  # from notity import msg,email,wechat
        cls = getattr(module,class_name)  # 利用反射 一切皆对象的思想 从文件中获取属性或者方法 cls = 一个个的类名
        obj = cls()  # 类实例化生成对象
        obj.send(content)  # 对象调方法
复制代码

email.py

class Email(object):
    def __init__(self):
        pass  # 发送邮件需要的代码配置

    def send(self,content):
        print('邮件通知:%s'%content)

msg.py

class  Msg(object):
    def __init__(self):
        pass  # 发送短信需要的代码配置

    def send(self,content):
        print('短信通知:%s' % content)

qq.py

class QQ(object):
    def __init__(self):
        pass  # 发送qq需要的代码准备

    def send(self,content):
        print('qq通知:%s'%content)

wechat.py

class WeChat(object):
    def __init__(self):
        pass  # 发送微信需要的代码配置

    def send(self,content):
        print('微信通知:%s'%content)

settings.py

NOTIFY_LIST = [
    'notify.email.Email',
    'notify.msg.Msg',
    # 'notify.wechat.WeChat',
    'notify.qq.QQ',
]

start.py

import notify

notify.send_all('国庆放假了 记住放八天哦')

原文地址:https://www.cnblogs.com/asdaa/p/11621830.html