Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 8, 2023 03:39
Show Gist options
  • Save code-boxx/53b9e67332e07a168cebb0bf8444ce44 to your computer and use it in GitHub Desktop.
Save code-boxx/53b9e67332e07a168cebb0bf8444ce44 to your computer and use it in GitHub Desktop.
Python Flask Star Rating System

PYTHON FLASK STAR RATING SYSTEM

https://code-boxx.com/star-rating-python-flask/

NOTES

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

IMAGE

hamburger

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) STAR RATING TABLE
CREATE TABLE `star_rating` (
`product_id` INTEGER NOT NULL,
`user_id` INTEGER NOT NULL,
`rating` INTEGER NOT NULL DEFAULT '1',
PRIMARY KEY (`product_id`,`user_id`)
);
-- (B) DUMMY DATA
INSERT INTO `star_rating` (`product_id`, `user_id`, `rating`) VALUES
(1, 900, 1),
(1, 901, 2),
(1, 902, 3),
(1, 903, 4),
(1, 904, 5);
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "stars.db"
SQLFILE = "S1A_database.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 = "stars.db"
# (B) HELPER - EXECUTE SQL QUERY
def query(sql, data):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
conn.close()
# (C) HELPER - FETCH
def fetch(sql, data=[]):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(sql, data)
results = cursor.fetchone()
conn.close()
return results
# (D) SAVE/UPDATE USER STAR RATING
def save(pid, uid, stars):
query(
"REPLACE INTO `star_rating` (`product_id`, `user_id`, `rating`) VALUES (?,?,?)",
[pid, uid, stars]
)
return True
# (E) GET USER STAR RATING FOR PRODUCT
def get(pid, uid):
res = fetch(
"SELECT * FROM `star_rating` WHERE `product_id`=? AND `user_id`=?",
[pid, uid]
)
return 0 if res is None else res[2]
# (F) GET AVERAGE RATING FOR PRODUCT
def avg(pid):
res = fetch("""
SELECT ROUND(AVG(`rating`), 2) `avg`, COUNT(`user_id`) `num`
FROM `star_rating`
WHERE `product_id`=?""", [pid])
return (0, 0) if res[0] is None else res
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response
import S2_star_lib as starz
# (A2) FLASK SETTINGS + INIT
HOST_NAME = "localhost"
HOST_PORT = 80
app = Flask(__name__)
# app.debug = True
# (A3) FIXED PRODUCT & USER ID FOR THIS DEMO
pid = 1
uid = 999
# (B) DUMMY PRODUCT HTML PAGE
@app.route("/")
def index():
# (B1) GET AVERAGE + USER STARS
astar = starz.avg(pid)
ustar = starz.get(pid, uid)
# (B2) RENDER HTML PAGE
return render_template("S4A_page.html", astar=astar, ustar=ustar)
# (C) SAVE STARS
@app.route("/save/", methods=["POST"])
def save():
data = dict(request.form)
starz.save(pid, uid, data["stars"])
return make_response("OK", 200)
# (D) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
<!DOCTYPE html>
<html>
<head>
<title>Demo Star Rating</title>
<meta charset="utf-8">
<script src="static/S4B_star.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="static/S4C_star.css">
</head>
<body>
<!-- (A) DUMMY PRODUCT -->
<div class="product">
<img class="img" src="static/hamburger.png">
<div class="name">Hamborger</div>
<div class="desc">Piece of meat and veggies with 2 pieces of bun.</div>
<div class="avg">Rating: {{ astar[0] }} ({{ astar[1] }} users)</div>
<div class="rate">Your rating: <div id="demo"></div></div>
</div>
<!-- (B) INIT STAR RATING -->
<script>
starry({
target: document.getElementById("demo"),
max: 5,
now: {{ ustar }},
click : stars => {
let data = new FormData();
data.append("stars", stars);
fetch("/save/", {
method: "post",
body: data
})
.then(res => res.text())
.then(txt => {
if (txt == "OK") { location.reload(); }
else { alert(txt); }
});
}
});
</script>
</body>
</html>
// STARRY() : CREATE STAR RATING
// target : target html element
// max : number of stars, default 5
// now : number of stars now, default 0
// disabled : cannot change number of stars/click, default false
// click : run this function when user click on star
function starry (instance) {
// (A) SET DEFAULTS
if (instance.max === undefined) { instance.max = 5; }
if (instance.now === undefined) { instance.now = 0; }
if (instance.now > instance.max) { instance.now = instance.max; }
if (instance.disabled === undefined) { instance.disabled = false; }
// (B) GENERATE STARS
instance.target.classList.add("starwrap");
for (let i=1; i<=instance.max; i++) {
// (B1) CREATE HTML STAR
let s = document.createElement("div");
s.className = "star";
instance.target.appendChild(s);
// (B2) HIGHLIGHT STAR
if (i <= instance.now) { s.classList.add("on"); }
if (!instance.disabled) {
// (B3) ON MOUSE OVER
s.onmouseover = () => {
let all = instance.target.getElementsByClassName("star");
for (let j=0; j<all.length; j++) {
if (j<i) { all[j].classList.add("on"); }
else { all[j].classList.remove("on"); }
}
};
// (B4) ON CLICK
if (instance.click) { s.onclick = () => instance.click(i); }
}
}
// (C) GET NUMBER OF SELECTED STARS
instance.target.getstars = () => instance.target.querySelectorAll(".on").length;
}
/* (A) ENTIRE PAGE */
* {
font-family: arial, sans-serif;
box-sizing: border-box;
}
body {
background: #d9d9d9;
}
/* (B) PRODUCT DOCKET */
.product {
padding: 20px;
max-width: 300px;
border: 2px solid #eee;
background: #fff;
}
.product .img {
display: block;
width: 100%;
}
.product .name {
font-size: 24px;
font-weight: 700;
margin-top: 10px;
}
.product .desc { color: #7c7c7c; }
.product .avg { margin: 15px 0 5px 0; }
.product .rate {
display: flex;
align-items: center;
}
/* (C) STAR RATING */
/* (C1) STAR RATING WRAPPER */
.starwrap { display: flex; }
/* (C2) STAR ICON */
.star {
font-family: "Material Icons" !important;
font-size: 24px; color: #d1d1d1;
font-style: normal; font-weight: normal; font-variant: normal;
text-transform: none; line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.star::before { content: "star"; }
.star.on { color: #ffe000; }
md templates
md static
move S4A_page.html templates
move S4B_star.js static
move S4C_star.css static
curl https://user-images.githubusercontent.com/11156244/281252790-6c573ecf-da53-401a-9dae-133b043b2fdc.png --ssl-no-revoke --output static/hamburger.png
virtualenv venv
call venv\Scripts\activate
pip install flask
python S1B_create.py
python S3_server.py
mkdir -m 777 templates
mkdir -m 777 static
mv ./S4A_page.html ./templates
mv ./S4B_star.js ./static
mv ./S4C_star.css ./static
curl https://user-images.githubusercontent.com/11156244/281252790-6c573ecf-da53-401a-9dae-133b043b2fdc.png --ssl-no-revoke --output ./static/hamburger.png
virtualenv venv
source "venv/bin/activate"
pip install flask
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