config.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from configparser import ConfigParser
  2. import os
  3. class Config:
  4. DEFAULT_XML_REFERENCE_TYPE = 'http://www.gzs.si/shemas/eslog/racun/1.6#Racun'
  5. DEFAULT_CONFIG_DIR = os.path.join(os.path.expanduser('~'), '.config')
  6. def __init__(self, config_file):
  7. self.config_file = os.path.join(self.DEFAULT_CONFIG_DIR, config_file)
  8. self.config = ConfigParser()
  9. self.config.read(self.config_file)
  10. self.errors = []
  11. def exists(self):
  12. return 'settings' in self.config and 'xmlschema' in self.config['settings'] and\
  13. 'certificate' in self.config['settings']
  14. def get_data(self):
  15. return {
  16. 'xmlreftype': self.config.get('settings', 'xmlreftype'),
  17. 'xmlschema': self.config.get('settings', 'xmlschema'),
  18. 'certificate': self.config.get('settings', 'certificate')
  19. }
  20. def verify_data(self):
  21. if not self.exists():
  22. self.errors.append('Config wasn\'t set up yet.')
  23. return False
  24. if not os.path.isfile(self.config['settings']['xmlschema']):
  25. self.errors.append('XML Schema file doesn\'t exist.')
  26. if not os.path.isfile(self.config['settings']['certificate']):
  27. self.errors.append('Certificate file doesn\'t exist.')
  28. return len(self.errors) == 0
  29. def get_errors(self):
  30. errors = self.errors.copy()
  31. self.errors.clear()
  32. return errors
  33. def save_data(self, config):
  34. if 'settings' not in self.config:
  35. self.config.add_section('settings')
  36. self.config.set('settings', 'xmlreftype', self.DEFAULT_XML_REFERENCE_TYPE)
  37. self.config.set('settings', 'xmlschema', config['xmlschema'])
  38. self.config.set('settings', 'certificate', config['certificate'])
  39. try:
  40. if not os.path.isfile(self.config_file):
  41. os.makedirs(self.DEFAULT_CONFIG_DIR, exist_ok=True)
  42. with open(self.config_file, 'w') as f:
  43. self.config.write(f)
  44. except:
  45. raise ConfigException('Cannot write config.')
  46. class ConfigException(Exception):
  47. pass