Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active October 7, 2023 06:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/45fd441ce7bb597294f6495769d51fb9 to your computer and use it in GitHub Desktop.
Save code-boxx/45fd441ce7bb597294f6495769d51fb9 to your computer and use it in GitHub Desktop.
Python Flask Seat Reservation System

PYTHON FLASK SEAT RESERVATION SYSTEM

https://code-boxx.com/seat-reservation-python-flask/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Create a templates folder, move S4A_seats.html inside.
    • Create a static folder, move S4B_seats.js and S4C_seats.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
    • 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) SEATS
CREATE TABLE `seats` (
`seat_id` TEXT NOT NULL,
`room_id` TEXT NOT NULL,
PRIMARY KEY (`seat_id`, `room_id`)
);
-- (B) SESSIONS
CREATE TABLE `sessions` (
`session_id` INTEGER PRIMARY KEY AUTOINCREMENT,
`room_id` TEXT NOT NULL,
`session_date` TEXT NOT NULL
);
CREATE INDEX `idx_room_id`
ON `sessions` (`room_id`);
CREATE INDEX `idx_session_date`
ON `sessions` (`session_date`);
-- (C) RESERVATIONS
CREATE TABLE `reservations` (
`session_id` INTEGER NOT NULL,
`seat_id` TEXT NOT NULL,
`user_id` INTEGER NOT NULL,
PRIMARY KEY (`session_id`,`seat_id`,`user_id`)
);
-- (D) DUMMY DATA
-- (D1) DUMMY SEATS
INSERT INTO `seats` (`seat_id`, `room_id`) VALUES
('A1', 'ROOM-A'),
('A2', 'ROOM-A'),
('A3', 'ROOM-A'),
('A4', 'ROOM-A'),
('B1', 'ROOM-A'),
('B2', 'ROOM-A'),
('B3', 'ROOM-A'),
('B4', 'ROOM-A'),
('C1', 'ROOM-A'),
('C2', 'ROOM-A'),
('C3', 'ROOM-A'),
('C4', 'ROOM-A');
-- (D2) DUMMY SESSION
INSERT INTO `sessions` (`session_id`, `room_id`, `session_date`) VALUES
(1, 'ROOM-A', '2077-06-05 08:00:00');
-- (D3) DUMMY RESERVATION
INSERT INTO `reservations` (`session_id`, `seat_id`, `user_id`) VALUES
('1', 'B2', '555'),
('1', 'A4', '888');
# (A) LOAD PACKAGES
import sqlite3, os
from sqlite3 import Error
# (B) DATABASE + SQL FILE
DBFILE = "seats.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 = "seats.db"
# (B) HELPER - RUN SQL QUERY
def query(sql, data):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(sql, data)
conn.commit()
conn.close()
# (C) HELPER - FETCH ALL
def select(sql, data=[]):
conn = sqlite3.connect(DBFILE)
cursor = conn.cursor()
cursor.execute(sql, data)
results = cursor.fetchall()
conn.close()
return results
# (D) GET SEATS FOR GIVEN SESSION
def get(sid):
res = []
for row in select("""SELECT sa.`seat_id`, r.`user_id` FROM `seats` sa
LEFT JOIN `sessions` se USING (`room_id`)
LEFT JOIN `reservations` r USING(`seat_id`)
WHERE se.`session_id`=?
ORDER BY sa.`seat_id`""", [sid]):
res.append(row)
return res
# (E) SAVE RESERVATION
def save (sid, uid, seats):
sql = "INSERT INTO `reservations` (`session_id`, `seat_id`, `user_id`) VALUES "
data = []
for s in seats:
sql += "(?,?,?),"
data.append(sid)
data.append(s)
data.append(uid)
sql = sql[:-1]
query(sql, data)
return True
# (A) INIT
# (A1) LOAD MODULES
from flask import Flask, render_template, request, make_response
import S2_seat_lib as seatr
import json
# (A2) FLASK SETTINGS + INIT
HOST_NAME = "localhost"
HOST_PORT = 80
app = Flask(__name__)
# app.debug = True
# (A3) FIXED SESSION & USER ID FOR THIS DEMO
uid = 999
sid = 1
# (B) SEAT RESERVATION HTML PAGE
@app.route("/")
def index():
# (B1) GET SEATS
seats = seatr.get(sid)
# (B2) RENDER HTML PAGE
return render_template("S4A_seats.html", seats=seats)
# (C) SAVE RESERVATION
@app.route("/save", methods=["POST"])
def save():
data = dict(request.form)
seats = json.loads(data["seats"])
seatr.save(sid, uid, seats)
return make_response("OK", 200)
# (D) START
if __name__ == "__main__":
app.run(HOST_NAME, HOST_PORT)
<!DOCTYPE html>
<html>
<head>
<title>Seat Reservation</title>
<!-- (A) CSS + JS -->
<script src="static/S4B_seats.js"></script>
<link rel="stylesheet" href="static/S4C_seats.css">
</head>
<body>
<!-- (B) SEAT LAYOUT -->
<div id="layout">
{% for seat in seats %}
<div
{% if seat[1] is none %}
class="seat" onclick="reserve.toggle(this)"
{% else %}
class="seat taken"
{% endif %}
>{{ seat[0] }}</div>
{% endfor %}
</div>
<!-- (C) LEGEND -->
<div id="legend">
<div class="seat"></div> <div class="txt">Available</div>
<div class="seat taken"></div> <div class="txt">Taken</div>
<div class="seat selected"></div> <div class="txt">Your Chosen Seats</div>
</div>
<!-- (D) SAVE SELECTION -->
<button id="save" onclick="reserve.save()">Reserve Seats</button>
</body>
</html>
var reserve = {
// (A) CHOOSE THIS SEAT
toggle : seat => seat.classList.toggle("selected"),
// (B) SAVE RESERVATION
save : () => {
// (B1) GET SELECTED SEATS
let selected = document.querySelectorAll("#layout .selected");
// (B2) ERROR!
if (selected.length == 0) { alert("No seats selected."); }
// (B3) SELECTED SEATS
else {
// (B3-1) GET SELECTED SEAT NUMBERS
let seats = [];
for (let s of selected) { seats.push(s.innerHTML); }
// (B3-2) SEND TO SERVER
let data = new FormData();
data.append("seats", JSON.stringify(seats));
data.append("KEY", "VALUE"); // add more data as required
fetch("/save", {
method: "POST",
body : data
})
.then(res => res.text())
.then(txt => {
// DO WHATEVER IS REQUIRED
// SEND CUSTOMER TO THANK YOU PAGE?
// PAYMENT FIRST?
alert(txt);
});
}
}
};
/* (A) SEAT & "COLOR CODE" */
.seat {
text-align: center;
padding: 20px 10px;
border-radius: 10px;
background: #f1f1f1;
}
.taken { background: #df0000; color: #fff; }
.selected { background: #87ff96; }
/* (B) SEATS LAYOUT */
#layout {
max-width: 400px;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
margin-bottom: 20px;
}
/* (C) LEGEND */
#legend {
display: grid;
grid-gap: 10px;
grid-template-columns: 50px auto ;
}
#legend .txt {
display: flex;
align-items: center;
}
/* (D) SAVE */
#save {
font-size: 20px;
margin-top: 20px;
padding: 10px 20px;
border: 0;
color: #fff;
background: #00479f;
}
/* (X) DOES NOT MATTER */
* {
font-family: arial, sans-serif;
box-sizing: border-box;
}
md templates
md static
move S4A_seats.html templates
move S4B_seats.js static
move S4C_seats.css static
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_seats.html ./templates
mv ./S4B_seats.js ./static
mv ./S4C_seats.css ./static
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