131 lines
2.7 KiB
Python
131 lines
2.7 KiB
Python
import hashlib
|
|
from datetime import date
|
|
|
|
from flask import Blueprint, redirect, render_template, request, url_for
|
|
|
|
from .database import get_db
|
|
|
|
bp = Blueprint("public", __name__)
|
|
|
|
|
|
def get_todays_question():
|
|
db = get_db()
|
|
today = date.today().isoformat()
|
|
|
|
return db.execute(
|
|
"""
|
|
SELECT id, question, option_a, option_b, date
|
|
FROM questions
|
|
WHERE date = ?
|
|
LIMIT 1
|
|
""",
|
|
(today,),
|
|
).fetchone()
|
|
|
|
|
|
@bp.route("/")
|
|
def home():
|
|
question = get_todays_question()
|
|
|
|
return render_template(
|
|
"public/index.html",
|
|
question=question,
|
|
)
|
|
|
|
|
|
@bp.route("/vote", methods=["POST"])
|
|
def vote():
|
|
qid = request.form.get("qid")
|
|
selected_vote = request.form.get("vote")
|
|
|
|
if not qid or selected_vote not in {"A", "B"}:
|
|
return redirect(url_for("public.home"))
|
|
|
|
ip = request.remote_addr or ""
|
|
voter_hash = hashlib.sha256(ip.encode()).hexdigest()
|
|
|
|
db = get_db()
|
|
question = get_todays_question()
|
|
|
|
if question is None or str(question["id"]) != str(qid):
|
|
return redirect(url_for("public.home"))
|
|
|
|
existing = db.execute(
|
|
"""
|
|
SELECT id
|
|
FROM votes
|
|
WHERE voter_hash = ?
|
|
AND question_id = ?
|
|
""",
|
|
(voter_hash, qid),
|
|
).fetchone()
|
|
|
|
if existing is None:
|
|
db.execute(
|
|
"""
|
|
INSERT INTO votes (question_id, vote, voter_hash)
|
|
VALUES (?, ?, ?)
|
|
""",
|
|
(qid, selected_vote, voter_hash),
|
|
)
|
|
db.commit()
|
|
|
|
return redirect(url_for("public.results"))
|
|
|
|
|
|
@bp.route("/results")
|
|
def results():
|
|
question = get_todays_question()
|
|
|
|
if question is None:
|
|
return render_template(
|
|
"public/results.html",
|
|
question=None,
|
|
votes_a=0,
|
|
votes_b=0,
|
|
percent_a=0,
|
|
percent_b=0,
|
|
total=0,
|
|
)
|
|
|
|
db = get_db()
|
|
|
|
votes_a = db.execute(
|
|
"""
|
|
SELECT COUNT(*)
|
|
FROM votes
|
|
WHERE question_id = ?
|
|
AND vote = 'A'
|
|
""",
|
|
(question["id"],),
|
|
).fetchone()[0]
|
|
|
|
votes_b = db.execute(
|
|
"""
|
|
SELECT COUNT(*)
|
|
FROM votes
|
|
WHERE question_id = ?
|
|
AND vote = 'B'
|
|
""",
|
|
(question["id"],),
|
|
).fetchone()[0]
|
|
|
|
total = votes_a + votes_b
|
|
|
|
if total == 0:
|
|
percent_a = 0
|
|
percent_b = 0
|
|
else:
|
|
percent_a = round(votes_a / total * 100)
|
|
percent_b = round(votes_b / total * 100)
|
|
|
|
return render_template(
|
|
"public/results.html",
|
|
question=question,
|
|
votes_a=votes_a,
|
|
votes_b=votes_b,
|
|
percent_a=percent_a,
|
|
percent_b=percent_b,
|
|
total=total,
|
|
)
|