from uuid import uuid4 import mysql.connector class Database: def __init__(self, app): self.db = mysql.connector.connect( host=app.config["DB_HOSTNAME"], user=app.config["DB_USERNAME"], password=app.config["DB_PASSWORD"], database=app.config["DB_DATABASE"] ) self.cur = self.db.cursor() def create_session(self, username, password): self.cur.execute("SELECT user_id FROM utilisateurs WHERE username=%s AND password=%s", (username, password)) if result := self.cur.fetchall(): user_id = result[0][0] else: return None uuid = str(uuid4()) self.cur.execute("INSERT INTO sessions (session_id, user_id) VALUES (%s, %s)", (uuid, user_id)) self.db.commit() return uuid def destroy_session(self, uuid): self.cur.execute("DELETE FROM sessions WHERE session_id=%s", (uuid,)) self.db.commit() def check_connection(self, uuid): self.cur.execute("DELETE FROM sessions WHERE expiry_date <= CURRENT_TIMESTAMP") self.cur.execute("SELECT session_id FROM sessions WHERE session_id=%s", (uuid,)) return self.cur.fetchall() def __del__(self): self.cur.close() self.db.close() class User: def __init__(self, user_id, username, nom, prenom, creation_date): self.id = user_id self.username = username self.nom = nom self.prenom = prenom self.creation_date = creation_date class Session: def __init__(self, db, uuid): self.db = db self.uuid = uuid self.user = self.get_user() def get_user(self): self.db.cur.execute("SELECT utilisateurs.user_id, username, nom, prenom, creation_date FROM utilisateurs " "JOIN sessions ON utilisateurs.user_id=sessions.user_id WHERE session_id=%s", (self.uuid,)) result = self.db.cur.fetchall() return User(*result[0]) def fetch_grades(self): self.db.cur.execute("SELECT matieres.libelle, devoirs.libelle, date, coefficient, valeur, maximum FROM notes " "JOIN devoirs ON notes.id_devoir=devoirs.id_devoir " "JOIN matieres ON devoirs.id_matiere=matieres.id_matiere WHERE id_eleve=%s", (self.user.id,)) result = self.db.cur.fetchall() dico = {} for note in result: if note[0] in dico: dico[note[0]].append(note) else: dico[note[0]] = [note] return dico