importlib应用 - django
2024-09-03 09:44:00
背景
仿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..")
最新文章
- express中的路由
- JS区分移动端和PC
- Esfog_UnityShader教程_UnityShader语法实例浅析
- Twitter Storm安装配置(Ubuntu系统)单机版
- Android课程---Android Studio的一些小技巧
- gridView--GridView关于间距的属性值介绍
- Eclipse 插件 —— RunJettyRun 的下载、安装与使用
- 尝试一下用MARKDOWN嵌入代码
- RubyGems使用
- C++中new和不new的区别
- Windows系统安装MySQL
- INS-20802
- AIX7.1环境打补丁缺少bash OPATCHAUTO-72049
- Swing——布局管理器
- python练习册 0002随机生成验证
- Fedora 25-64位操作系统中安装配置Hyperledger Fabric过程
- XP环境下C# 调用Pocess.start()时提示文件找不到的错误解决办法
- 介绍一款jquery ui组件gijgo(含tree树状结构、grid表格),特点:简易、文档全清晰易懂、示例代码
- python call so
- Nginx 的 docker 部署