from app import db from app.models.poll import Poll, PollAnswer from collections import Counter class SimplePoll(Poll): """Poll with only one answer allowed""" __tablename__ = 'simplepoll' # Names of templates template = 'simplepoll.html' __mapper_args__ = { 'polymorphic_identity': __tablename__, } def __init__(self, author, title, choices, **kwargs): choices = [Choice(i, t) for i, t in enumerate(choices)] super().__init__(author, title, choices, **kwargs) # Mandatory methods def vote(self, user, request): try: choice_id = int(request.form['pollanwsers']) except (KeyError, ValueError): return None answer = PollAnswer(self, user, choice_id) return answer @property def results(self): values = {c: 0 for c in self.choices} counter = Counter(values) answers = [self.choice_from_id(a.answer) for a in self.answers] counter.update(answers) return counter # Custom method def choice_from_id(self, id): for c in self.choices: if c.id == id: return c return None class Choice(): def __init__(self, id, title): self.id = id self.title = title