def _mymodel_delete(sender, instance, **kwargs): """ When a PicklePersistedModel is deleted, also delete its pickle file :param sender: :param instance: :param kwargs: :return: """ if isinstance(instance, PicklePersistedModel): filepath = pickle_path(instance.id, instance.__class__.__name__) print('Delete {}'.format(filepath)) if os.path.isfile(filepath): os.remove(filepath) else: warning('File {} doesnot exist.'.format(filepath))
def load(self): """ Load the persisted data on to the model from its pickle file Not to be called when the model is being constructed :return: None """ if self.id: fpath = pickle_path(self.id, self.__class__.__name__) if os.path.isfile(fpath): with open(fpath, 'rb') as f: mdict = pickle.load(f) for attr in self._meta.attrs: # _attr = '_{}'.format(attr) setattr(self, attr, mdict[attr]) self._loaded = True else: warning('Can\'t restore data for {} #{}. File {} not found' .format(self.__class__.__name__, self.id, fpath))
def save(self, *args, **kwargs): """ Save the object and then use its ID to store a pickle file contaning all the attrs as declared Pickle file will be stored in user_data/pickle/<class name>/ :param args: :param kwargs: :return: None """ super(PicklePersistedModel, self).save(*args, **kwargs) fpath = pickle_path(self.id, self.__class__.__name__) ensure_parent_folder_exists(fpath) mdict = {} for attr in self._meta.attrs: mdict[attr] = getattr(self, attr) with open(fpath, 'wb') as f: pickle.dump(mdict, f, pickle.HIGHEST_PROTOCOL)