2021-02-19 22:07:31 +01:00
|
|
|
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
|
2021-02-20 00:33:34 +01:00
|
|
|
def vote(self, user, request):
|
|
|
|
try:
|
|
|
|
choice_id = int(request.form['pollanwsers'])
|
|
|
|
except (KeyError, ValueError):
|
|
|
|
return None
|
|
|
|
|
|
|
|
answer = PollAnswer(self, user, choice_id)
|
2021-02-19 22:07:31 +01:00
|
|
|
return answer
|
|
|
|
|
|
|
|
@property
|
|
|
|
def results(self):
|
|
|
|
values = {c: 0 for c in self.choices}
|
|
|
|
counter = Counter(values)
|
2021-02-20 00:33:34 +01:00
|
|
|
answers = [self.choice_from_id(a.answer) for a in self.answers]
|
|
|
|
counter.update(answers)
|
2021-02-19 22:07:31 +01:00
|
|
|
return counter
|
|
|
|
|
2021-02-20 00:33:34 +01:00
|
|
|
# Custom method
|
|
|
|
def choice_from_id(self, id):
|
|
|
|
for c in self.choices:
|
|
|
|
if c.id == id:
|
|
|
|
return c
|
|
|
|
return None
|
2021-02-19 22:07:31 +01:00
|
|
|
|
|
|
|
class Choice():
|
|
|
|
def __init__(self, id, title):
|
|
|
|
self.id = id
|
|
|
|
self.title = title
|