1
0
Fork 0
mirror of https://codeberg.org/Mo8it/AdvLabDB.git synced 2024-11-08 21:21:06 +00:00
AdvLabDB/advlabdb/model_dependent_funs.py

79 lines
2.3 KiB
Python
Raw Normal View History

2022-05-16 20:20:36 +00:00
# Functions dependent on advlabdb.models
from flask import flash, url_for
from flask_admin.menu import MenuLink
2021-06-02 21:43:41 +00:00
from flask_security import current_user
2022-05-16 20:20:36 +00:00
from sqlalchemy import select
2022-05-08 19:26:25 +00:00
from . import app, db
from .models import Semester
2021-05-17 20:36:24 +00:00
2022-05-16 16:35:42 +00:00
def sortedSemestersStartingWithNewest(limit=0):
# Inserting an older semester is not allowed!
# Therefore, the id is enough.
stmt = select(Semester).order_by(Semester.id.desc())
if limit > 0:
stmt = stmt.limit(limit)
return db.session.execute(stmt).scalars()
def lastSemester():
return sortedSemestersStartingWithNewest(limit=1).first()
2022-04-12 13:00:12 +00:00
def setUserActiveSemester(semester):
if semester is None:
flash(f"Can not change the active semester to None!", "error")
return
if current_user.active_semester != semester:
try:
current_user.active_semester = semester
db.session.commit()
except Exception as ex:
flash(str(ex), "error")
2021-07-11 11:48:13 +00:00
db.session.rollback()
2021-07-11 11:48:13 +00:00
else:
flash(f"Active semester changed to {semester.repr()}!", "warning")
def initActiveSemesterMenuLinks(space):
with app.app_context():
try:
2022-05-16 16:37:57 +00:00
semesters = sortedSemestersStartingWithNewest()
for semester in semesters:
space.add_link(
MenuLink(
name=semester.repr(),
url=url_for("set_semester") + "?semester_id=" + str(semester.id),
category="Active semester",
)
)
except Exception as ex:
print(
"ERROR: The Semester table does not exist yet! Therefore, menu links could not be generated. You can ignore this error if you are just initializing the database."
)
else:
space.add_link(MenuLink(name="Logout", url=url_for("security.logout")))
2021-11-30 00:36:19 +00:00
def reportBadAttempt(message):
print("BAD ATTEMPT:", message) # TODO: Log
2022-05-16 19:48:04 +00:00
def get_count(table):
return db.session.scalar(select(func.count()).select_from(table))
def active_semester_repr():
active_semester = current_user.active_semester
repr = active_semester.repr()
if active_semester != lastSemester():
flash(f"You are in the old semester {repr}!", "warning")
return repr