Guest User

Untitled

a guest
May 21st, 2018
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. import json
  2. import time
  3. import logging
  4. from collections import UserDict
  5.  
  6. class AutoReloadConfig(UserDict):
  7. """
  8. A dictionary that automatically reloads itself from a file.
  9. On each call to __getitem__(), check if config is older than reload_period and if yes then reload from file.
  10.  
  11. Example:
  12. # load from config.json every 60s
  13. config = AutoReloadConfig("config.json", 60)
  14.  
  15. # gets value from config (and reloads beforehand if last get was before 60s)
  16. test = config["test"]
  17. """
  18. def __init__(self, config_filename, reload_period = 60):
  19. self._logger = logging.getLogger("config")
  20.  
  21. self._reload_period = reload_period
  22. self._filename = config_filename
  23.  
  24. self._age = 0
  25.  
  26. def __getitem__(self, key):
  27. if self._age + self._reload_period < time.time():
  28. self._reload()
  29. return super().__getitem__(key)
  30.  
  31. def _reload(self):
  32. try:
  33. with open(self._filename) as fp:
  34. config = json.load(fp)
  35.  
  36. self._age = time.time()
  37.  
  38. # set data used by UserDict
  39. self.data = config
  40. self._logger.debug("config reloaded")
  41. except:
  42. self._logger.exception("failed to reload configuration from file \"" + self._filename + "\".")
Add Comment
Please, Sign In to add comment