setting.py
# 导入自定义公共配置
DJANGO_CONF_MODULE = 'conf.common_settings'
try:
_module = __import__(DJANGO_CONF_MODULE, globals(), locals(), ['*'])
except ImportError as e:
raise ImportError("Could not import config '%s' (Is it on sys.path?): %s"
% (DJANGO_CONF_MODULE, e))
for _setting in dir(_module):
if _setting == _setting.upper():
locals()[_setting] = getattr(_module, _setting)
ini文件方式--配置导入(common_settings.py)
# # 定义微服务名称
SERVER_NAME = "zet_pub_job"
# 导入ini配置
# SERVER_NAME = "zet_pub_demo"
# try:
# from conf.parse_ini import *
#
# load_common_config(locals())
# load_server_config(locals())
# except ImportError:
# pass
parse_ini.py
import configparser
from pathlib import Path
from django.conf import settings
ini_dir_parent = Path(__file__).resolve().parent.parent.parent
# 加载公共配置
def load_common_config(settings_module):
common_ini_name = "service.ini"
paths = ["conf", common_ini_name]
ini_path = ini_dir_parent.joinpath(*paths)
if Path.exists(ini_path):
config = configparser.ConfigParser(interpolation=configparser.BasicInterpolation())
config.read(ini_path)
parse_ini_config(config, settings_module)
# 加载本微服务配置
def load_server_config(settings_module):
# server_name = locals().get("SERVER_NAME")
server_name = settings_module.get("SERVER_NAME")
server_ini_name = "service_" + server_name + ".ini"
paths = ["conf", server_ini_name]
ini_path = ini_dir_parent.joinpath(*paths)
if Path.exists(ini_path):
config = configparser.ConfigParser(interpolation=configparser.BasicInterpolation())
config.read(ini_path)
parse_ini_config(config, settings_module)
# 解析ini配置并加入django-setting
def parse_ini_config(config, settings_module):
"""
:param config: configparser.ConfigParser实例
:return:
"""
sections = config.sections()
for section in sections:
if section.find(':') > 0:
parameter = section.split(":", 1)[0]
parameter_key = section.split(":", 1)[1]
if hasattr(settings, parameter):
if parameter_key not in getattr(settings, parameter):
setattr(getattr(settings, parameter), parameter_key, {})
for key, value in config.items(section):
getattr(settings, parameter)[parameter_key][key.upper()] = value
else:
setattr(settings, parameter, {})
setattr(getattr(settings, parameter), parameter_key, {})
for key, value in config.items(section):
getattr(settings, parameter)[parameter_key][key.upper()] = value
elif section == "base":
for key, value in config.items(section):
setattr(settings, key, value)
else:
parameter = section
if not hasattr(settings, parameter):
setattr(settings, parameter, {})
for key, value in config.items(section):
getattr(settings, parameter)[key.upper()] = value
settings_module[parameter] = getattr(settings, parameter)