1 #!/usr/bin/env python 2 3 """ 4 User profile management. 5 6 Copyright (C) 2015 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from imiptools.config import PREFERENCES_DIR 23 from imiptools.filesys import fix_permissions, FileBase 24 from os.path import exists, isdir 25 from os import makedirs 26 27 class Preferences(FileBase): 28 29 "A simple preferences file manager." 30 31 def __init__(self, user, store_dir=None): 32 FileBase.__init__(self, store_dir or PREFERENCES_DIR) 33 self.user = user 34 35 def get(self, name, default=None): 36 37 """ 38 Return the value for 'name', with absent entries providing a default of 39 None or any indicated 'default'. 40 """ 41 42 try: 43 return self[name] 44 except KeyError: 45 return default 46 47 def __getitem__(self, name): 48 49 "Return the value for 'name', raising a KeyError if absent." 50 51 filename = self.get_object_in_store(self.user, name) 52 if not filename or not exists(filename): 53 raise KeyError, name 54 55 f = open(filename) 56 try: 57 return f.read().strip() 58 finally: 59 f.close() 60 61 def __setitem__(self, name, value): 62 63 "Set for 'name' the given 'value'." 64 65 filename = self.get_object_in_store(self.user, name) 66 if not filename: 67 return False 68 69 f = open(filename, "w") 70 try: 71 f.write(value) 72 finally: 73 f.close() 74 fix_permissions(filename) 75 76 return True 77 78 # vim: tabstop=4 expandtab shiftwidth=4