新增YAML配置文件和解析封装

This commit is contained in:
chenzuoqing 2021-12-16 19:40:59 +08:00
parent 7b26d9ddbd
commit bae428c975
5 changed files with 76 additions and 3 deletions

6
conf.yaml Normal file
View File

@ -0,0 +1,6 @@
ops1:
server: http://10.2.2.10:8000
project_list: /api/items/list/
headers:
X-Token: 51ab21fa323a11eca1af000c2993d583

View File

@ -5,3 +5,5 @@ flask-mongoengine==1.0.0
flask-redis==0.4.0
Flask-RESTful==0.3.9
jsonschema==4.2.1
PyYAML==6.0
requests==2.26.0

View File

@ -1,3 +1,12 @@
import os.path
from common.conf import load_yaml
# 项目目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
CONFIG_FILE = os.path.join(os.path.dirname(BASE_DIR), "conf.yaml")
CONFIG: dict = load_yaml(CONFIG_FILE, raise_exception=True, default={})
VERSION = "v1"
INSTANCE = "9e5da0b3-565f-11ec-b095-18c04d9eb245"

View File

@ -6,7 +6,7 @@ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SECRET_KEY = 'cf036e50524a11ecb4a618c04d9eb245'
JSONIFY_PRETTYPRINT_REGULAR = False
RESTFUL_JSON = {'separators': (',', ':'), 'indent': 0}
RESTFUL_JSON = {'separators': (',', ':'), 'indent': 4}
# mongodb 地址
MONGODB_SETTINGS = {
@ -18,7 +18,7 @@ REDIS_URL = "redis://:@10.2.2.10:6379/1"
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asctime)s %(levelname)s %(module)s:%(funcName)s %(process)d %(thread)d %(message)s'
@ -44,12 +44,26 @@ LOGGING = {
'backupCount': 5,
'formatter': 'verbose'
},
'common': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler',
'filename': os.path.join(os.path.dirname(BASE_DIR), 'logs/common.log'),
'encoding': 'utf-8',
'maxBytes': 1024 * 1024 * 5,
'backupCount': 5,
'formatter': 'verbose',
},
},
'loggers': {
'root': {
'handlers': ['file_app'],
'level': 'DEBUG',
'propagate': True,
'propagate': False,
},
'common': {
'handlers': ['common'],
'level': 'DEBUG',
'propagate': False,
}
}
}

42
src/common/conf.py Normal file
View File

@ -0,0 +1,42 @@
"""
conf.yaml 的辅助方法
"""
import yaml
from settings import common
def load_yaml(filename, raise_exception=False, default=None):
"""
:param filename:
:param raise_exception: 是否触发异常
:param default: 默认值不触发异常时使用
:return:
"""
data = default
filename = str(filename)
try:
with open(filename, 'r') as f:
data = yaml.safe_load(f)
except Exception as e:
if raise_exception:
raise e
return data if data else default
def get_conf_section(name, default=None):
"""从配置文件中获取配置项"""
try:
return common.CONFIG.get(name, default)
except:
return default
def get_conf_section_opt(section_name, opt_name, default=None):
"""从配置文件中获取配置项,需要是字典"""
try:
section = common.CONFIG.get(section_name, {})
data = section.get(opt_name, default)
except:
return default
return data