storage.py 1.7 KB

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