基于django中间件实现插拔式
start.py
from notify import *
send_all('好嗨哦')
settings.py
NOTIFY_LIST = [
'notify.email.Email',
'notify.msg.Msg',
'notify.wechat.WeChat',
'notify.qq.Qq',
]
notify __init__.py
import settings
import importlib
def send_all(content):
for path in settings.NOTIFY_LIST: # "notify.email.Email"
module_path, cls_name = path.rsplit('.',maxsplit=1)
# module_path = 'notify.email' cls_name = "Email"
md = importlib.import_module(module_path) # from notify import email
cls = getattr(md,cls_name) # 获取到文件中类的名字
obj = cls() # 实力化产生一个个类的对象
obj.send(content)
notify email.py
class Email(object):
def __init__(self):
pass # 发送邮件需要的前期准备
def send(self,content):
print('邮件通知:%s'%content)
仿django settings
目录结构
conf
- settings.py
lib
- conf
- __init__.py
- global_settings.py
start.py
start.py
import os
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
if __name__ == '__main__':
# os.environ.setdefault('xxx','conf.settings')
os.environ['xxx'] = 'conf.settings'
from lib.conf import settings
print(settings.NAME)
lib conf __init__.py
import importlib
from lib.conf import global_settings
import os
class Settings(object):
def __init__(self):
for name in dir(global_settings):
if name.isupper():
setattr(self,name,getattr(global_settings,name))
# 获取暴露给用户的配置文件字符串路径
module_path = os.environ.get('xxx')
md = importlib.import_module(module_path) # md = settings
for name in dir(md):
if name.isupper():
k = name
v = getattr(md,name)
setattr(self,k,v)
settings = Settings()
conf settings.py
NAME = '我是暴露给用户的自定义配置'