Skip to content

Instantly share code, notes, and snippets.

@gubser
Last active May 17, 2018 05:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gubser/2587c8ce5d8b5adf19229e5668835660 to your computer and use it in GitHub Desktop.
Save gubser/2587c8ce5d8b5adf19229e5668835660 to your computer and use it in GitHub Desktop.
License: MIT
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 + "\".")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment