Convert old style except blocks to except Exception as variable: blocks
[htsworkflow.git] / htsworkflow / util / config_helper.py
1 """Helper functions to manage ini file settings.
2 """
3 import logging
4 import os
5 import ConfigParser
6
7 from htsworkflow.util.api import make_django_secret_key
8
9 LOGGER = logging.getLogger(__name__)
10
11 class HTSWConfig(ConfigParser.SafeConfigParser):
12     '''Customization of SafeConfigParser that can open and save itself.
13     '''
14     def __init__(self, path=[os.path.expanduser("~/.htsworkflow.ini"),
15                              '/etc/htsworkflow.ini',]):
16         # ConfigParser isn't a new-style class? lame
17         # super(ConfigParser.SafeConfigParser, self).__init__()
18         ConfigParser.SafeConfigParser.__init__(self)
19         read_path = self.read(path)
20         if len(read_path) > 0:
21             self.filename = read_path[0]
22         else:
23             self.filename = path[0]
24
25     def setdefaultsecret(self, section, key, length=216):
26         '''return current secret key, creating a new key if needed
27         '''
28         if not self.has_section(section):
29             self.add_section(section)
30
31         if not self.has_option(section, key):
32             secret = make_django_secret_key(length)
33             self.set(section, key, secret)
34             self.save()
35         return self.get(section, key)
36
37     def save(self):
38         try:
39             ini_stream = open(self.filename, 'w')
40             self.write(ini_stream)
41             ini_stream.close()
42         except IOError as e:
43             LOGGER.info("Error saving setting: %s" % (str(e)))