Squashed 'paste-framework/' content from commit 34e8684
git-subtree-dir: paste-framework git-subtree-split: 34e8684c4bc3cebbe177509f42ab4ef5b5425a7a
This commit is contained in:
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
读取配置信息的方法集合。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from paste.util import ufile, udict
|
||||
|
||||
GLOBAL_CONFIG = None
|
||||
"""
|
||||
全局单例配置系统。
|
||||
"""
|
||||
|
||||
|
||||
def load_config() -> dict:
|
||||
"""
|
||||
生成配置 JSON 对象。
|
||||
|
||||
:return: JSON 对象
|
||||
"""
|
||||
global GLOBAL_CONFIG
|
||||
if GLOBAL_CONFIG is None:
|
||||
config_file = os.path.abspath(os.path.join(os.path.curdir, 'config.json'))
|
||||
GLOBAL_CONFIG = json.loads(ufile.read_to_buffer(config_file))
|
||||
return GLOBAL_CONFIG
|
||||
|
||||
|
||||
def get_config_by_path(path: str, default=None):
|
||||
"""
|
||||
读取配置参数。若 path 存在则返回值;若 path 不存在,且没有默认值,则抛出异常,否则返回默认值。
|
||||
|
||||
:param path: 字典中的 key 路径,以"."号分隔
|
||||
:param default: 默认值,为 None 时表示未设置,此时若键名不存在,会抛出异常
|
||||
"""
|
||||
config = load_config()
|
||||
_result = udict.get_by_path(config, path, default)
|
||||
if _result is None:
|
||||
if default is None:
|
||||
raise AssertionError('未读取到配置参数: %s' % path)
|
||||
else:
|
||||
return default
|
||||
return _result
|
||||
|
||||
|
||||
def get_config(key: str, default=None):
|
||||
"""
|
||||
读取配置参数。若 key 存在则返回值;若 key 不存在,且没有默认值,则抛出异常,否则返回默认值。
|
||||
|
||||
:param key: 键名,或配置字典中的 path
|
||||
:param default: 默认值,为 None 时表示未设置,此时若键名不存在,会抛出异常
|
||||
"""
|
||||
return get_config_by_path(path=key, default=default)
|
||||
Reference in New Issue
Block a user