Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 7, 2023 06:49
Show Gist options
  • Select an option

  • Save code-boxx/6931ebecd0798d4a9614fcb9e52988e6 to your computer and use it in GitHub Desktop.

Select an option

Save code-boxx/6931ebecd0798d4a9614fcb9e52988e6 to your computer and use it in GitHub Desktop.
Python Flask Voting System

PYTHON FLASK SEAT VOTING SYSTEM

https://code-boxx.com/voting-system-python/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a templates folder, move S4_vote.html inside.
    • Create a static folder, move S4_vote.css inside.
    • Create a virtual environment - virtualenv venv.
    • Activate the virtual environment - venv\scripts\activate (Windows) venv/bin/activate (Mac/Linux)
    • Install Flask - pip install flask flask-session
    • Create the database - python S1B_create.py
    • Start the Flask server - python S3_server.py
  2. Access http://localhost in your browser.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) QUESTIONS TABLE
CREATE TABLE questions (
qid INTEGER,
txt TEXT NOT NULL,
PRIMARY KEY("qid" AUTOINCREMENT)
);
-- (B) OPTIONS TABLE
CREATE TABLE options (
oid INTEGER,
qid INTEGER NOT NULL,
txt TEXT NOT NULL,
votes INTEGER DEFAULT 0,
PRIMARY KEY("oid" AUTOINCREMENT)
);
CREATE INDEX idx_qid ON options (qid);
-- (C) DUMMY DATA
INSERT INTO questions (txt) VALUES ("What is your favorite meme animal?");
INSERT INTO options (qid, txt, votes) VALUES
(1, "Birb", 11), (1, "Doge", 22), (1, "Cate", 33), (1, "Snek", 44);
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "votes.db"
SQLFILE = "S1A_votes.sql"
# (C) DELETE OLD DATABASE IF EXIST
if os.path.exists(DBFILE):
os.remove(DBFILE)
# (D) IMPORT SQL
conn = sqlite3.connect(DBFILE)
with open(SQLFILE) as f:
conn.executescript(f.read())
conn.commit()
conn.close()
print("Database created!")
# (A) LOAD SQLITE MODULE
import sqlite3
DBFILE = "votes.db"
# (B) GET QUESTION + OPTIONS + VOTES
def get(qid):
# (B1) RETURNS A DICTIONARY (NONE ON ERROR/NOT FOUND)
res = {
"q" : "", # QUESTION
"o" : {}, # OPTIONS, OID : TEXT
"v" : {} # VOTES, OID : NUMBER OF VOTES
}
# (B2) GET QUESTION
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute("SELECT txt FROM questions WHERE qid=?", (qid,))
data = cursor.fetchone()
if data is None:
return None
# (B3) GET OPTIONS
res["q"] = data[0]
cursor.execute("SELECT oid, txt, votes FROM options WHERE qid=?", (qid,))
data = cursor.fetchall()
if len(data)==0:
return None
for row in data:
res["o"][row[0]] = row[1]
res["v"][row[0]] = row[2]
# (B4) RETURN RESULT
conn.close()
return res
# (C) SAVE VOTE
def save(qid, oid, oldid):
# (C1) GET CURRENT VOTES COUNT
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute("SELECT oid, votes FROM options WHERE qid=?", (qid,))
data = {}
for r in cursor.fetchall():
data[r[0]] = r[1]
# (C2) UPDATE OLD VOTE COUNT
if oldid is not None:
count = data[oldid] - 1
count = count if count>0 else 0
cursor.execute("UPDATE options SET votes=? WHERE qid=? AND oid=?", (count, qid, oldid,))
# (C3) UPDATE NEW VOTE COUNT
count = data[oid] + 1
cursor.execute("UPDATE options SET votes=? WHERE qid=? AND oid=?", (count, qid, oid,))
# (C4) DONE
conn.commit()
conn.close()
return True
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, session, render_template, request
from flask_session import Session
import S2_lib as votes
# (A2) FLASK SETTINGS + INIT
HOST_NAME = "localhost"
HOST_PORT = 80
app = Flask(__name__)
# app.debug = True
app.secret_key = "VERY-SECRET-KEY"
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
# (B) VOTES PAGE
@app.route("/", methods=["GET", "POST"])
def index():
# (B1) INIT
qid = 1 # QUESTION ID, FIXED TO 1 IN THIS EXAMPLE
if "vote" not in session: # SESSION - KEEP TRACK OF VOTES MADE
session["vote"] = {}
# (B2) SAVE VOTE ON FORM SUBMIT
if request.method == "POST":
oid = int(request.values.get("vote"))
oldid = None if qid not in session["vote"] else session["vote"][qid]
votes.save(qid, oid, oldid)
session["vote"][qid] = oid
# (B3) GET QUESTION FROM DB
data = votes.get(qid)
if data is None:
return "ERROR!"
data["qid"] = qid
# (B4) RENDER PAGE
return render_template("S4_vote.html", **data)
# (C) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
.poll-docket {
max-width: 400px;
padding: 20px;
border-radius: 10px;
background: #eee;
}
.poll-question {
font-size: 20px;
font-weight: 700;
margin-bottom: 10px;
}
.poll-option {
display: block;
width: 100%;
padding: 10px 0;
}
.poll-go {
font-size: 18px;
color: #fff;
background: #981818;
width: 100%;
padding: 10px;
margin-top: 10px;
border: 0;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Python Voting System</title>
<link rel="stylesheet" href="static/S4_vote.css">
</head>
<body>
<form method="post" class="poll-docket">
<!-- (A) QUESTION -->
<div class="poll-question">{{ q }}</div>
<!-- (B) OPTIONS -->
{% for oid, txt in o.items() %}
<label class="poll-option">
<input type="radio" name="vote" value="{{ oid }}" required
{% if session["vote"][qid] is defined and oid==session["vote"][qid] %}
checked
{% endif %}>
<span class="poll-text">{{txt}}</span>
<span class="poll-votes">({{v[oid]}})</span>
</label>
{% endfor %}
<!-- (C) SUBMIT -->
<input type="submit" class="poll-go" value="Go!">
</form>
</body>
</html>
md templates
md static
move S4_vote.html templates
move S4_vote.css static
virtualenv venv
call venv\Scripts\activate
pip install flask flask-session
python S1B_create.py
python S3_server.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S4_vote.html ./templates
mv ./S4_vote.css ./static
virtualenv venv
source "venv/bin/activate"
pip install flask flask-session
python S1B_create.py
python S3_server.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment