-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
81 lines (59 loc) · 2.11 KB
/
Copy pathapp.py
File metadata and controls
81 lines (59 loc) · 2.11 KB
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
79
80
81
#!/usr/bin/env python3
from flask import Flask, render_template, request
from election import Election
import json
import atexit
def init():
"""Initializes required data"""
global config
global election
# Read config from file
with open("config.json") as f:
config = json.load(f)
# Set limit to number of candidates if no limit is set
if config["max_candidates"] == -1:
config["max_candidates"] = len(config["candidates"])
# Create Election object from config
election = Election(config["candidates"], config["out_filename"], config["max_candidates"])
# Initialize data
init()
# Initialize app
app = Flask(__name__)
def password_is_valid(password: str):
"""Returns True if password is valid, False otherwise"""
return password in config["passwords"]
def remove_password(password: str):
"""Removes password from the list of allowed passwords"""
config["passwords"].remove(password)
@app.route("/")
def ballot():
return render_template("ballot.html", title=config["title"], candidates=config["candidates"], max_candidates=config["max_candidates"])
@app.route("/vote", methods=["POST"])
def vote():
data = request.form
password = data.get("password")
# Was the vote successful?
success = False
# Check password validity
if password_is_valid(password):
candidates = data.getlist("candidate")
# Only submit vote if there are no duplicates
if (len(set(candidates)) == len(candidates)):
# Try to vote for the selected candidates
success = election.vote(candidates)
if success:
print("Vote received")
# If voting was successful, disable the password and write the new results
remove_password(password)
return render_template("success.html")
else:
print("Voting attempt failed")
return render_template("error.html")
def on_exit():
"""Exit handler"""
print("Exit requested")
print("Saving votes...")
election.write_json()
print(f"Votes saved to {config['out_filename']}")
# Save election results on exit
atexit.register(on_exit)