Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import json
- import time
- import logging
- from collections import UserDict
- class AutoReloadConfig(UserDict):
- """
- A dictionary that automatically reloads itself from a file.
- On each call to __getitem__(), check if config is older than reload_period and if yes then reload from file.
- Example:
- # load from config.json every 60s
- config = AutoReloadConfig("config.json", 60)
- # gets value from config (and reloads beforehand if last get was before 60s)
- test = config["test"]
- """
- def __init__(self, config_filename, reload_period = 60):
- self._logger = logging.getLogger("config")
- self._reload_period = reload_period
- self._filename = config_filename
- self._age = 0
- def __getitem__(self, key):
- if self._age + self._reload_period < time.time():
- self._reload()
- return super().__getitem__(key)
- def _reload(self):
- try:
- with open(self._filename) as fp:
- config = json.load(fp)
- self._age = time.time()
- # set data used by UserDict
- self.data = config
- self._logger.debug("config reloaded")
- except:
- self._logger.exception("failed to reload configuration from file \"" + self._filename + "\".")
Add Comment
Please, Sign In to add comment