storage.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. import cPickle as pickle
  4. import logging
  5. import os
  6. class Storage:
  7. data = None
  8. def __init__(self, storage_dir):
  9. self.logger = logging.getLogger('Storage')
  10. self.storage_dir = storage_dir
  11. self.logger.debug('Using storage at \'{0}\''.format(storage_dir))
  12. self.storage_file = open(os.path.join(storage_dir, 'storage.dat'), 'a+b')
  13. try:
  14. self.storage_file.seek(0, os.SEEK_SET)
  15. self.data = pickle.load(self.storage_file)
  16. except EOFError:
  17. self.logger.warn('The storage file was empty. I\'ll assume this is the first start with this storage directory.')
  18. except Exception as err:
  19. self.logger.error('Loading the storage failed. Please resolve the error and/or remove the storage file \'{0}\': {1}'.format(
  20. os.path.join(storage_dir, self.storage_file.name),
  21. str(err),
  22. ))
  23. raise err
  24. if self.data is None:
  25. self.data = {}
  26. self.logger.info('Opened storage with ' + str(len(self.data)) + ' entries.')
  27. def save(self):
  28. self.storage_file.seek(0, os.SEEK_SET)
  29. self.storage_file.truncate()
  30. pickle.dump(self.data, self.storage_file, protocol=2)
  31. self.storage_file.flush()
  32. def close(self):
  33. self.save()
  34. self.storage_file.close()
  35. self.data = None