Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
296 lines (262 loc) · 10.4 KB
/
Copy pathapp.py
File metadata and controls
296 lines (262 loc) · 10.4 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""
app.py — CS 6083 Spring 2026 — Flight Search Web Application
Uses SQLite by default. To switch to PostgreSQL, replace get_db() with
a psycopg2 connection and use %s placeholders instead of ?.
"""
from flask import Flask, render_template, request, jsonify
import sqlite3, os
app = Flask(__name__)
DB_PATH = os.path.join(os.path.dirname(__file__), "flights.db")
# ── Database helper ──────────────────────────────────────────────────────────
def get_db():
"""Return a SQLite connection with row-factory for dict-like access."""
con = sqlite3.connect(DB_PATH)
con.row_factory = sqlite3.Row
return con
# ── Routes ───────────────────────────────────────────────────────────────────
@app.route("/")
def index():
"""Start page: search form."""
db = get_db()
airports = db.execute(
"SELECT airport_code, name, city FROM Airport ORDER BY airport_code"
).fetchall()
db.close()
return render_template("index.html", airports=airports)
@app.route("/search")
def search():
"""
Part (b): Return all flights matching origin, destination, date range.
Query params: origin, dest, date_from, date_to
"""
origin = request.args.get("origin", "").upper().strip()
dest = request.args.get("dest", "").upper().strip()
date_from = request.args.get("date_from", "")
date_to = request.args.get("date_to", "")
if not (origin and dest and date_from and date_to):
return render_template("results.html", flights=[], search={})
db = get_db()
query = """
SELECT
f.flight_number,
f.departure_date,
fs.origin_code,
fs.dest_code,
fs.departure_time,
fs.duration,
fs.airline_name,
f.plane_type,
ao.name AS origin_name,
ad.name AS dest_name
FROM Flight f
JOIN FlightService fs ON f.flight_number = fs.flight_number
JOIN Airport ao ON fs.origin_code = ao.airport_code
JOIN Airport ad ON fs.dest_code = ad.airport_code
WHERE fs.origin_code = ?
AND fs.dest_code = ?
AND f.departure_date BETWEEN ? AND ?
ORDER BY f.departure_date, fs.departure_time
"""
rows = db.execute(query, (origin, dest, date_from, date_to)).fetchall()
db.close()
search_ctx = {
"origin": origin, "dest": dest,
"date_from": date_from, "date_to": date_to
}
return render_template("results.html",
flights=[dict(r) for r in rows],
search=search_ctx)
@app.route("/flight/<flight_number>/<departure_date>")
def flight_detail(flight_number, departure_date):
"""
Part (c): Show capacity and available seats for a specific flight instance.
"""
db = get_db()
flight = db.execute("""
SELECT
f.flight_number,
f.departure_date,
f.plane_type,
fs.airline_name,
fs.origin_code,
fs.dest_code,
fs.departure_time,
fs.duration,
ac.capacity,
ao.name AS origin_name,
ad.name AS dest_name
FROM Flight f
JOIN FlightService fs ON f.flight_number = fs.flight_number
JOIN Aircraft ac ON f.plane_type = ac.plane_type
JOIN Airport ao ON fs.origin_code = ao.airport_code
JOIN Airport ad ON fs.dest_code = ad.airport_code
WHERE f.flight_number = ?
AND f.departure_date = ?
""", (flight_number, departure_date)).fetchone()
if not flight:
db.close()
return render_template("detail.html", flight=None, booked=0,
available=0, passengers=[])
booked_count = db.execute("""
SELECT COUNT(*) AS cnt FROM Booking
WHERE flight_number = ? AND departure_date = ?
""", (flight_number, departure_date)).fetchone()["cnt"]
passengers = db.execute("""
SELECT p.passenger_name, b.seat_number
FROM Booking b
JOIN Passenger p ON b.pid = p.pid
WHERE b.flight_number = ? AND b.departure_date = ?
ORDER BY b.seat_number
""", (flight_number, departure_date)).fetchall()
db.close()
f = dict(flight)
available = f["capacity"] - booked_count
return render_template("detail.html",
flight=f,
booked=booked_count,
available=available,
passengers=[dict(p) for p in passengers])
@app.route("/metadata")
def metadata():
import re
db = get_db()
tables = [r["name"] for r in db.execute(
"SELECT name FROM sqlite_master WHERE type='table' ORDER BY name"
).fetchall()]
# (a) Hardcoded from schema knowledge since db_init.py has no FK constraints
fk_tables = [
{
"table_name": "Flight",
"distinct_referenced_tables": 2,
"references": "Aircraft, FlightService"
},
{
"table_name": "Booking",
"distinct_referenced_tables": 2,
"references": "Flight, Passenger"
}
]
# (b) Hardcoded from schema knowledge since all types are stored as TEXT
date_cols = [
{"table_name": "FlightService", "column_name": "departure_time", "data_type": "TIME"},
{"table_name": "FlightService", "column_name": "duration", "data_type": "INTERVAL"},
{"table_name": "Flight", "column_name": "departure_date", "data_type": "DATE"},
{"table_name": "Booking", "column_name": "departure_date", "data_type": "DATE"},
]
# (c) Distinct values per column in Flight — fully dynamic, works fine
flight_cols = [c["name"] for c in db.execute("PRAGMA table_info(Flight)").fetchall()]
distinct_vals = []
for col in flight_cols:
cnt = db.execute(f"SELECT COUNT(DISTINCT {col}) AS cnt FROM Flight").fetchone()["cnt"]
distinct_vals.append({"attribute": col, "distinct_values": cnt})
# (d) Composite PKs — fully dynamic, works fine
composite_keys = []
for t in tables:
cols = db.execute(f"PRAGMA table_info({t})").fetchall()
pk_cols = sorted([c for c in cols if c["pk"] > 0], key=lambda x: x["pk"])
pk_names = [c["name"] for c in pk_cols]
if len(pk_names) > 1:
composite_keys.append({
"table_name": t,
"pk_column_count": len(pk_names),
"pk_columns": ", ".join(pk_names)
})
# (e) Columns containing "name" — fully dynamic, works fine
name_cols = []
for t in tables:
cols = db.execute(f"PRAGMA table_info({t})").fetchall()
for c in cols:
if "name" in c["name"].lower():
name_cols.append({
"table_name": t,
"column_name": c["name"],
"data_type": c["type"]
})
db.close()
return render_template("metadata.html",
fk_tables=fk_tables,
date_cols=date_cols,
distinct_vals=distinct_vals,
composite_keys=composite_keys,
name_cols=name_cols)
@app.route("/query", methods=["GET", "POST"])
def query_runner():
from flask import request
results = []
columns = []
error = None
query = ""
if request.method == "POST":
query = request.form.get("query", "").strip()
if query:
db = get_db()
try:
if query.upper().startswith("SELECT"):
rows = db.execute(query).fetchall()
if rows:
columns = list(rows[0].keys())
results = [list(r) for r in rows]
else:
error = "Query ran successfully but returned no results."
else:
db.execute(query)
db.commit()
error = "Query executed successfully!"
except Exception as e:
error = f"Error: {str(e)}"
finally:
db.close()
return render_template("query.html",
results=results,
columns=columns,
error=error,
query=query)
@app.route("/admin")
def admin():
db = get_db()
airports = db.execute("SELECT airport_code FROM Airport ORDER BY airport_code").fetchall()
aircraft = db.execute("SELECT plane_type FROM Aircraft ORDER BY plane_type").fetchall()
db.close()
return render_template("admin.html", airports=airports, aircraft=aircraft)
@app.route("/admin/add_airport", methods=["POST"])
def add_airport():
from flask import redirect, url_for
airport_code = request.form["airport_code"].upper().strip()
name = request.form["name"].strip()
city = request.form["city"].strip()
country = request.form["country"].strip()
db = get_db()
db.execute("INSERT INTO Airport VALUES (?, ?, ?, ?)",
(airport_code, name, city, country))
db.commit()
db.close()
return redirect(url_for("admin"))
@app.route("/admin/add_aircraft", methods=["POST"])
def add_aircraft():
from flask import redirect, url_for
plane_type = request.form["plane_type"].strip()
capacity = int(request.form["capacity"])
db = get_db()
db.execute("INSERT INTO Aircraft VALUES (?, ?)", (plane_type, capacity))
db.commit()
db.close()
return redirect(url_for("admin"))
@app.route("/admin/add_flight", methods=["POST"])
def add_flight():
from flask import redirect, url_for
db = get_db()
db.execute("INSERT INTO Flight VALUES (?, ?, ?)",
(
request.form["flight_number"].upper().strip(),
request.form["departure_date"].strip(),
request.form["plane_type"].strip()
))
db.commit()
db.close()
return redirect(url_for("admin"))
if __name__ == "__main__":
# Initialize DB on first run
from db_init import init_db
if not os.path.exists(DB_PATH):
init_db()
app.run(debug=True, port=5000)