-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathelection.py
78 lines (65 loc) · 2.43 KB
/
election.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
from flask import Flask, render_template, request
import json
from settings import *
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html", candidates=candidates, allow_empty_submissions=allow_empty_submissions, organisation=organisation)
@app.route("/vote", methods=["POST"])
def vote():
key = request.form.get("KEY")
# Load the key data
with open("all_keys.json") as f:
all_keys = json.load(f)
try:
with open("done_keys.json") as f:
done_keys = json.load(f)
except FileNotFoundError:
done_keys = []
# Check if the key is valid and not already used
if key not in all_keys:
return render_template("failure.html", message="Invalid key!", organisation=organisation)
if key in done_keys:
return render_template("failure.html", message="You have voted already!", organisation=organisation)
# Append the key to the list of used keys
done_keys.append(key)
with open("done_keys.json", "w") as f:
json.dump(done_keys, f)
# Load the existing votes data
try:
with open("votes.json") as file:
data = json.load(file)
except FileNotFoundError:
data = {
pos:{
cand: 0 for cand in candidates[pos]
} for pos in candidates
}
# Process the votes for each position
for position in request.form:
if position == "KEY":
continue
candidate = request.form.get(position)
if candidate:
# replace _ with " " in positions
# position =
if position not in data:
data[position] = {}
if candidate not in data[position]:
data[position][candidate] = 0
data[position][candidate] += 1
# Save the updated votes data
with open("votes.json", "w") as file:
json.dump(data, file, indent=4)
# Render the success page
return render_template("success.html", organisation=organisation)
@app.route("/live")
def results():
try:
with open("votes.json") as file:
data = json.load(file)
except FileNotFoundError:
return render_template("results.html", message="No votes yet!", results={}, organisation=organisation)
return render_template("results.html", message=None, results=data, organisation=organisation)
if __name__ == "__main__":
app.run(debug=debug, host=IP, port=PORT)