config.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. # This file a part of SHM. Copyright (C) Tom Li 2013.
  3. # License: LGPL version 3 or later.
  4. from configparser import ConfigParser
  5. class Config():
  6. def __init__(self, path, user=None):
  7. self._config = ConfigParser()
  8. self._config.read(path)
  9. if not self._config.has_section('users'):
  10. self._config['users'] = {}
  11. self.user = user
  12. self._open = True
  13. self._path = path
  14. @property
  15. def domain(self):
  16. try:
  17. return eval(self._config['users'][self.user])
  18. except KeyError:
  19. self._config['users'][self.user] = str([])
  20. return eval(self._config['users'][self.user])
  21. @domain.setter
  22. def domain(self, domain):
  23. self._config['users'][self.user] = str(domain)
  24. def append_domain(self, domain):
  25. if domain in self.domain:
  26. return
  27. new_domain_list = self.domain
  28. new_domain_list.append(domain)
  29. self.domain = new_domain_list
  30. def remove_domain(self, domain):
  31. if domain not in self.domain:
  32. return
  33. new_domain_list = self.domain
  34. new_domain_list.remove(domain)
  35. self.domain = new_domain_list
  36. def save(self):
  37. if not self._open:
  38. return
  39. with open(self._path, "w+") as config_file:
  40. self._config.write(config_file)
  41. self._open = False
  42. def __del__(self):
  43. self.save()