-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
398 lines (338 loc) · 16.3 KB
/
app.py
File metadata and controls
398 lines (338 loc) · 16.3 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# Copyright 2025 Harikrishna Srinivasan
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from flask import (Flask, make_response, redirect, render_template,
request, session, url_for)
from typehints import NotFound, Optional, Response, Union
import fetch_data
import mysql_connector as sql
import secrets
import show_data
app = Flask(__name__, template_folder="templates")
app.jinja_env.filters.pop("attr", None)
app.jinja_env.autoescape = True
app.secret_key = secrets.token_hex(16)
DAYS: tuple[str, ...] = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
timetables: list[dict[str, Union[bool, int, str]]] = []
@app.before_request
def check_login(login: str = "login") -> Optional[Response]:
if not session.get("logged_in") and request.endpoint != login:
return redirect(url_for(login))
return None
def nocache(view):
def no_cache_response(*args, **kwargs):
response = make_response(view(*args, **kwargs))
response.headers["Cache-Control"] = "no-cache, no-store, " \
"must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
no_cache_response.__name__ = view.__name__
return no_cache_response
@app.route("/login", methods=["GET", "POST"])
@nocache
def login(
index: str = "index",
) -> Union[Response, str]:
if request.method == "GET":
if session.get("logged_in"):
return redirect(url_for(index))
else:
return render_template("./login.html", user="User",
auth="/login", role="User")
elif request.form.get("user") and request.form.get("password"):
try:
sql.connect(user=request.form["user"],
password=request.form["password"])
if sql.db_connector and sql.cursor:
session["logged_in"] = True
return redirect(url_for(index))
except sql.pymysql.err.OperationalError:
return render_template(
"./login.html",
user="User",
auth="/login",
error_message="Invalid username or password",
role="User")
except Exception:
return render_template("./failed.html",
reason="Unknown error occurred")
return render_template("./failed.html",
reason="Login information not entered properly!")
@app.route("/faculty")
@nocache
def log_faculty() -> Union[Response, str]:
if not session.get("faculty") or not session.get("faculty_details"):
return render_template("./login.html", user="ID", userType="number",
auth="/auth_faculty", role="faculty")
return redirect(url_for("faculty_details"))
@app.route("/auth_faculty", methods=["POST"])
def auth_faculty() -> Union[Response, str]:
if (user := request.form.get("user")) \
and (password := request.form.get("password")):
try:
if sql.cursor:
session["faculty_details"] = fetch_data.get_faculty_details(
sql.cursor,
id=int(user),
password=password)
session["faculty"] = True
return redirect(url_for("show_faculty_details"))
return render_template("./failed.html", reason="Unauthorized Login!")
except AssertionError:
return render_template("./login.html", user="ID", userType="number",
auth="/auth_faculty", role="faculty",
error_message="Invalid ID or Password")
except Exception:
return render_template("./login.html", user="ID", userType="number",
auth="/auth_faculty", role="faculty",
error_message="Invalid ID")
return render_template("./failed.html",
reason="Login information not entered properly!")
@app.route("/home")
@app.route("/")
def index() -> str:
return render_template("./index.html")
@app.route("/about")
def about() -> str:
return render_template("./about.html")
@app.route("/campus")
def show_campuses() -> str:
if sql.cursor:
campuses = sorted(show_data.get_campuses(sql.cursor),
key=lambda campus: campus["id"])
return render_template("./campus.html",
campuses=campuses)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/campus/<string:campus>")
def show_schools(campus: str) -> str:
if sql.cursor:
campus_id = show_data.get_campus_id(sql.cursor, campus=campus)
if campus_id is None:
return render_template("./failed.html",
reason="No such Campus found!!")
return render_template("./school.html",
schools=show_data.get_schools(
sql.cursor,
campus_id=campus_id),
campus=campus)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/school/<string:campus>/<string:school>")
def show_buildings(campus: str, school: str) -> str:
if sql.cursor:
campus_id = show_data.get_campus_id(sql.cursor, campus=campus)
if campus_id is None:
return render_template("./failed.html",
reason="No such Campus found!!")
school_id = show_data.get_school_id(sql.cursor, campus_id=campus_id,
school=school)
if school_id is None:
return render_template("./failed.html",
reason=f"No such School found in {campus}!")
return render_template("./building.html",
buildings=show_data.get_buildings(
sql.cursor,
school_id=school_id),
school=school)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/degree")
def show_degrees() -> str:
if sql.cursor:
return render_template("./degree.html",
degrees=show_data.get_degrees(sql.cursor))
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/programme")
def show_programmes() -> str:
if sql.cursor:
return render_template("./programme.html",
programmes=show_data.get_programmes(sql.cursor))
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/degree/<string:degree>")
def show_degree_programmes(degree: str) -> str:
if sql.cursor:
programmes = show_data.get_programmes(sql.cursor, degree=degree)
return render_template("./stream.html",
degree=degree, streams=programmes)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/<string:degree>/<string:stream>")
def show_years(degree: str, stream: str) -> str:
if sql.cursor:
duration = show_data.get_degree_duration(sql.cursor, degree=degree)
if not isinstance(duration, int):
raise TypeError("Duration expected as int not as "
f"{type(duration).__name__}")
return render_template("./year.html", degree=degree, stream=stream,
years=range(1, duration+1))
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/<string:degree>/<string:stream>/<int:year>")
def show_programme_campuses(degree: str, stream: str, year: int) -> str:
if sql.cursor:
programme_id = show_data.get_programme_id(sql.cursor,
degree=degree, stream=stream)
campuses = show_data.get_campuses(sql.cursor,
programme_id=programme_id)
return render_template("./programme_campus.html", campuses=campuses,
degree=degree, stream=stream, year=year)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/<string:degree>/<string:stream>/<int:year>", methods=["POST"])
def show_sections(degree: str, stream: str, year: int) -> str:
if sql.cursor:
campus_id = int(request.form["campus_id"])
sections = fetch_data.get_sections(sql.cursor, campus_id=campus_id,
degree=degree, stream=stream,
year=year)
return render_template("./section.html", degree=degree, stream=stream,
year=year, sections=sections)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/<string:degree>/<string:stream>/<int:year>/<string:section>",
methods=["POST"])
def show_courses(degree: str, stream: str, year: int, section: str) -> str:
if sql.cursor:
section_id = int(request.form["section_id"])
faculty_courses = fetch_data.get_faculty_section_courses(
sql.cursor,
section_id=section_id)
courses = {}
for fc in faculty_courses:
course_code = fc["course_code"]
if course_code in courses:
continue
courses[course_code] = fetch_data.get_course(sql.cursor,
code=course_code)
courses[course_code].update(
{"is_elective": "Department Elective" if
fetch_data.is_elective(sql.cursor,
course_code=course_code,
section_id=section_id)
else "Department Core"})
return render_template("./course.html", courses=courses,
degree=degree, stream=stream,
year=year, section=section,
section_id=section_id)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/faculty/details")
def show_faculty_details() -> str:
if sql.cursor:
if not session.get("faculty") or not session.get("faculty_details"):
return render_template("./failed.html",
reason="Illegal access or value is missing")
faculty = session["faculty_details"]
campus = show_data.get_campus_name(sql.cursor, id=faculty["campus_id"])
return render_template("./faculty.html", faculty=faculty, campus=campus)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/faculty/timetable")
def show_faculty_timetable() -> str:
if sql.cursor:
global timetables
if not session.get("faculty") or not session.get("faculty_details"):
return render_template("./failed.html",
reason="Illegal access or value is missing")
id = session["faculty_details"]["id"]
if faculty := fetch_data.get_faculty_name(sql.cursor, id=id):
pass
periods = fetch_data.get_periods(sql.cursor)
for period in periods:
period["time_range"] = f"{period['start_time']}-{period['end_time']}"
grid = {day: {period["id"]: "" for period in periods} for day in DAYS}
if not timetables:
timetables = fetch_data.get_timetables(sql.cursor)
_timetables = [t for t in timetables if t["faculty_id"] == id]
for row in _timetables:
day = row["day"]
period_id = row["period_id"]
content = f"{row['course_code']}-{row['faculty_id']}({row['room_no']})"
if row["is_lab"]:
content += "(Lab)"
if content:
if grid[day][period_id]:
grid[day][period_id] += "/"
grid[day][period_id] += content
course_data = {}
for fc in _timetables:
course_code = fc["course_code"]
course = fetch_data.get_course(sql.cursor, code=course_code)
if course_code not in course_data:
course_data[course_code] = {
"name": course["name"],
"faculties": set(),
"credits": course["credits"],
"L": course["L"],
"P": course["P"],
"T": course["T"],
}
course_data[course_code]["faculties"].add(f"{faculty}({fc['faculty_id']})")
for course in course_data.values():
course["faculties"] = ", ".join(course["faculties"])
title = "Timetable"
return render_template("./timetable.html", title=title, days=DAYS, periods=periods, grid=grid, course_data=course_data)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/timetable", methods=["POST"])
def show_timetables() -> str:
if sql.cursor:
global timetables
section_id = int(request.form["section_id"])
periods = fetch_data.get_periods(sql.cursor)
section = fetch_data.get_section(sql.cursor, section_id=section_id)
campus = show_data.get_campus_name(sql.cursor, id=section["campus_id"])
title = f"{campus}-{section['degree']} {section['stream'] or ''} {section['section']} (Year {section['year']})"
for period in periods:
period["time_range"] = f"{period['start_time']}-{period['end_time']}"
grid = {day: {period["id"]: "" for period in periods} for day in DAYS}
if not timetables:
timetables = fetch_data.get_timetables(sql.cursor)
_timetables = [t for t in timetables if t["section_id"] == section_id]
for row in _timetables:
day = row["day"]
period_id = row["period_id"]
content = f"{row['course_code']}-{row['faculty_id']}({row['room_no']})"
if row["is_lab"]:
content += "(Lab)"
if content:
if grid[day][period_id]:
grid[day][period_id] += "/"
grid[day][period_id] += content
course_data = {}
for fc in _timetables:
faculty = fetch_data.get_faculty_name(sql.cursor,
id=fc["faculty_id"])
course_code = fc["course_code"]
course = fetch_data.get_course(sql.cursor, code=course_code)
if course_code not in course_data:
course_data[course_code] = {
"name": course["name"],
"faculties": set(),
"credits": course["credits"],
"L": course["L"],
"P": course["P"],
"T": course["T"],
}
course_data[course_code]["faculties"].add(f"{faculty}({fc['faculty_id']})")
for course in course_data.values():
course["faculties"] = ", ".join(course["faculties"])
return render_template("./timetable.html", days=DAYS, periods=periods, grid=grid, course_data=course_data, title=title)
return render_template("./failed.html", reason="Unknown error occurred")
@app.route("/logout")
def logout() -> Response:
session.clear()
sql.close()
return redirect(url_for("login"))
@app.errorhandler(404)
def page_not_found(error: NotFound) -> tuple[str, int]:
return (render_template("./404.html"), 404)
if __name__ == "__main__":
app.config.update(
SESSION_COOKIE_SAMESITE="Strict",
SESSION_COOKIE_HTTPONLY=True,
SESSION_COOKIE_SECURE=True
)
app.run(host="0.0.0.0", port=5000, debug=False)