zoukankan      html  css  js  c++  java
  • 更好的利用配置文件和importlib

    需求:做不同的操作时只需修改配置文件即可完成

    # message/email.py
    
    from .base import Base  # 子类必须实现send方法,否则抛出异常
    
    class Email(Base):
        """
        发送邮件提醒相关
        """
        def __init__(self):
            """
            邮箱相关数据初始化
            """
            self.username = 'zhou'
            self.pwd = '123'
    
        def send(self,msg):
            pass
    #message/msg.py
    
    from .base import Base
    
    class Msg(Base):
        """
        发送短信提醒相关
        """
    
        def __init__(self):
            """
            短信相关数据初始化
            """
            self.username = 'asdf'
            self.pwd = 'asdf'
    
        def send(self, msg):
            pass
    # settings.py
    
    MSG_LIST = [
        "utils.message.email.Email",
        "utils.message.msg.Msg",
        "utils.message.wechat.WeChat",
    ]
    # message/init.py
    
    import settings
    import importlib
    
    def send_msgs(msg):
    
        for path in settings.MSG_LIST:
            m,c = path.rsplit('.',maxsplit=1)
            md = importlib.import_module(m) #导入模块
            obj = getattr(md,c)() # 利用反射找到方法
            obj.send(msg)  # 执行方法
    #使用
    
    from message import send_msgs
    
    send_msgs("xxxxx")
  • 相关阅读:
    MySQL-基础知识整理
    设计模式-适配器模式
    MySQL
    MySQL-5.7 填坑
    MySQL
    Oracle
    SQL 注入
    Apache JMeter
    AppScan
    DNS 搜索
  • 原文地址:https://www.cnblogs.com/zhoujunhao/p/8617748.html
Copyright © 2011-2022 走看看