如已知某些配置会在之后的运行中可能被多次修改,则:
项目中业务代码不允许修改
配置文件可以允许修改
示例:
projict:
db:
mysql.py
sqlserver.py
app.py
settings.py
start.py
db:
#mysql.py class MySQLHelper(object): def fetchone(self): """ 链接MySQL,获取一条数据 :return: """ print('MySQL.fetchone') #sqlserver.py class SqlServerHelper(object): def fetchone(self): """ 链接SQLServer,获取一条数据 :return: """ print('SQLServer.fetchone')
settings:
# DB_PATH = "db.mysql.MySQLHelper" DB_PATH = "db.sqlserver.SqlServerHelper"
apps:
from projiect.settings import DB_PATH def func(): # 导入文件 # 反射 # DB_PATH = "db.mysql.MySQLHelper" module_path,cls_name = DB_PATH.rsplit('.',maxsplit=1) # 以字符串的形式导入模块 # from db import mysql import importlib module_obj = importlib.import_module(module_path) # 去模块中导入类 cls = getattr(module_obj,cls_name) # 类实例化 obj = cls() obj.fetchone() if __name__ == '__main__': func()