135 lines
2.2 KiB
Python
135 lines
2.2 KiB
Python
from flask import Flask, render_template, request, redirect
|
|
from datetime import date
|
|
import sqlite3
|
|
import hashlib
|
|
|
|
app = Flask(__name__)
|
|
|
|
DB = "questions.db"
|
|
|
|
|
|
def get_db():
|
|
return sqlite3.connect(DB)
|
|
|
|
|
|
@app.route("/")
|
|
def home():
|
|
|
|
conn = get_db()
|
|
cur = conn.cursor()
|
|
|
|
cur.execute("""
|
|
SELECT *
|
|
FROM questions
|
|
ORDER BY id DESC
|
|
LIMIT 1
|
|
""")
|
|
|
|
question = cur.fetchone()
|
|
|
|
conn.close()
|
|
|
|
return render_template(
|
|
"index.html",
|
|
question=question
|
|
)
|
|
|
|
|
|
@app.route("/vote", methods=["POST"])
|
|
def vote():
|
|
|
|
qid = request.form["qid"]
|
|
vote = request.form["vote"]
|
|
|
|
ip = request.remote_addr
|
|
|
|
voter_hash = hashlib.sha256(
|
|
ip.encode()
|
|
).hexdigest()
|
|
|
|
conn = get_db()
|
|
cur = conn.cursor()
|
|
|
|
cur.execute("""
|
|
SELECT *
|
|
FROM votes
|
|
WHERE voter_hash = ?
|
|
AND question_id = ?
|
|
""", (voter_hash, qid))
|
|
|
|
existing = cur.fetchone()
|
|
|
|
if not existing:
|
|
|
|
cur.execute("""
|
|
INSERT INTO votes
|
|
(question_id, vote, voter_hash)
|
|
VALUES (?, ?, ?)
|
|
""", (qid, vote, voter_hash))
|
|
|
|
conn.commit()
|
|
|
|
conn.close()
|
|
|
|
return redirect("/results")
|
|
|
|
|
|
@app.route("/results")
|
|
def results():
|
|
|
|
conn = get_db()
|
|
cur = conn.cursor()
|
|
|
|
cur.execute("""
|
|
SELECT *
|
|
FROM questions
|
|
ORDER BY id DESC
|
|
LIMIT 1
|
|
""")
|
|
|
|
question = cur.fetchone()
|
|
|
|
qid = question[0]
|
|
|
|
cur.execute("""
|
|
SELECT COUNT(*)
|
|
FROM votes
|
|
WHERE question_id = ?
|
|
AND vote = 'A'
|
|
""", (qid,))
|
|
|
|
votes_a = cur.fetchone()[0]
|
|
|
|
cur.execute("""
|
|
SELECT COUNT(*)
|
|
FROM votes
|
|
WHERE question_id = ?
|
|
AND vote = 'B'
|
|
""", (qid,))
|
|
|
|
votes_b = cur.fetchone()[0]
|
|
|
|
conn.close()
|
|
|
|
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(
|
|
"results.html",
|
|
question=question,
|
|
votes_a=votes_a,
|
|
votes_b=votes_b,
|
|
percent_a=percent_a,
|
|
percent_b=percent_b,
|
|
total=total
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run(debug=True) |