Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Snapshot(models.Model):
- tournament = models.ForeignKey('Tournament')
- name = models.CharField(null=True)
- created_at = models.DateTimeField()
- data = JSONField()
- class Memento:
- def __init__(self, snapshot_id, state):
- self.snapshot_id = snapshot_id # saved snapshot corresponding to this memento
- self.state = state # serialized schedule data dictionary
- class Originator:
- def __init__(self, tournament):
- self.tournament = tournament
- def set(self, snapshot_name=None):
- self.state = serialize_schedule(self.tournament)
- self.name = snapshot_name
- def create_memento(self):
- snapshot = Snapshot.objects.create(tournament=self.tournament, name=self.name,
- created_at=datetime.datetime.now(), data=self.state)
- return Memento(snapshot.id, self.state)
- def restore(self, memento):
- data = deserialize_schedule(self.tournament, memento.state)
- with transaction.atomic():
- delete_schedule() # delete current schedule
- create_schedule(data) # create schedule with the memento state data
- class Caretaker:
- def __init__(self, tournament):
- self.tournament = tournament
- self.originator = Originator(tournament)
- self.saved_states = list(Snapshot.objects.filter(tournament=tournament).values_list('id', flat=True))
- def create_snapshot(self, *args):
- self.originator.set(*args)
- memento = self.originator.create_memento()
- self.saved_states.append(memento.snapshot_id)
- def restore(self, snapshot_id):
- snapshot = self.tournament.snapshot_set.get(id=snapshot_id)
- memento = Memento(snapshot_id, snapshot.data)
- self.originator.restore(memento)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement