python动态全局缓存配置

在内存中缓存配置,但提供手动或自动刷新机制。
使用文件的修改时间戳(mtime)来判断文件是否更新,只有在文件更新时重新读取

import os
import json

_cached_config = None
_cached_config_mtime = None

def read_config():
    global _cached_config, _cached_config_mtime
    config_file = os.path.expanduser('~/.magic-pdf.json')

    if not os.path.exists(config_file):
        raise FileNotFoundError(f'{config_file} not found')

    mtime = os.path.getmtime(config_file)
    if _cached_config is None or _cached_config_mtime != mtime:
        with open(config_file, 'r', encoding='utf-8') as f:
            _cached_config = json.load(f)
            _cached_config_mtime = mtime

    return _cached_config

你可能感兴趣的:(python,缓存)