Python 实现抽象类的两种方式+邮件提醒+动态导入模块+反射(参考Django中间件源码)

时间:2022-01-10 09:33:39

实现抽象类的两种方式

方式一

from abc import ABCMeta
from abc import abstractmethod class BaseMessage(metaclass=ABCMeta): @abstractmethod
def send(self,subject,body,to,name):
pass

方式二

class BaseMessage(object):
def send(self, subject, body, to, name):
raise NotImplementedError('未实现send方法')

邮件提醒

import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from .base import BaseMessage class Email(BaseMessage):
def __init__(self):
self.email = "寄件人的邮箱地址"
self.user = "寄件人姓名"
self.pwd = '邮箱密码或SMTP授权码' def send(self,subject,body,to,name):
'''
:param subject: 主题
:param body: 内容
:param to:接受者
:param name:接受者姓名
:return:
''' msg = MIMEText(body, 'plain', 'utf-8') # 发送内容
msg['From'] = formataddr([self.user,self.email]) # 发件人
msg['To'] = formataddr([name, to]) # 收件人
msg['Subject'] = subject # 主题 server = smtplib.SMTP("smtp.126.com", 25) # SMTP服务
server.login(self.email, self.pwd) # 邮箱用户名和密码
server.sendmail(self.email, [to, ], msg.as_string()) # 发送者和接收者
server.quit()

动态导入模块+反射

settings

# ################## 自定义消息提醒的配置 ###################
MESSAGE_CLASSES = [
'utils.message.email.Email',
'utils.message.msg.Msg',
'utils.message.wx.WeChat',
'utils.message.dingding.DingDing',
]
import importlib
from django.conf import settings
def send_message(to,name,subject,body):
"""
短信、邮件、微信
:param to: 接受者
:param name: 接受者姓名
:param subject: 主题
:param body: 内容
:return:
"""
for cls_path in settings.MESSAGE_CLASSES:
# cls_path是字符串
module_path,class_name = cls_path.rsplit('.',maxsplit=1)  # 得到模块名的地址和模块里的一个类名(都是字符串)
m = importlib.import_module(module_path)  # 导入模块
obj = getattr(m,class_name)()·# 通过反射,得到字符串class_name对应的类,并实例化
obj.send(subject,body,to,name,)  # 执行对应的send方法