Advertisement
Guest User

Untitled

a guest
Oct 9th, 2018
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. class Snapshot(models.Model):
  2.     tournament = models.ForeignKey('Tournament')
  3.     name = models.CharField(null=True)
  4.     created_at = models.DateTimeField()
  5.     data = JSONField()
  6.  
  7.  
  8.  
  9. class Memento:
  10.     def __init__(self, snapshot_id, state):
  11.         self.snapshot_id = snapshot_id  # saved snapshot corresponding to this memento
  12.         self.state = state  # serialized schedule data dictionary
  13.  
  14.  
  15. class Originator:
  16.     def __init__(self, tournament):
  17.         self.tournament = tournament
  18.  
  19.     def set(self, snapshot_name=None):
  20.         self.state = serialize_schedule(self.tournament)
  21.         self.name = snapshot_name
  22.  
  23.     def create_memento(self):
  24.         snapshot = Snapshot.objects.create(tournament=self.tournament, name=self.name,
  25.                                            created_at=datetime.datetime.now(), data=self.state)
  26.         return Memento(snapshot.id, self.state)
  27.  
  28.     def restore(self, memento):
  29.         data = deserialize_schedule(self.tournament, memento.state)
  30.         with transaction.atomic():
  31.             delete_schedule()  # delete current schedule
  32.             create_schedule(data)  # create schedule with the memento state data
  33.  
  34.  
  35. class Caretaker:
  36.     def __init__(self, tournament):
  37.         self.tournament = tournament
  38.         self.originator = Originator(tournament)
  39.         self.saved_states = list(Snapshot.objects.filter(tournament=tournament).values_list('id', flat=True))
  40.  
  41.     def create_snapshot(self, *args):
  42.         self.originator.set(*args)
  43.         memento = self.originator.create_memento()
  44.         self.saved_states.append(memento.snapshot_id)
  45.  
  46.     def restore(self, snapshot_id):
  47.         snapshot = self.tournament.snapshot_set.get(id=snapshot_id)
  48.         memento = Memento(snapshot_id, snapshot.data)
  49.         self.originator.restore(memento)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement