Skip to content

Commit

Permalink
now support for all CRUD
Browse files Browse the repository at this point in the history
  • Loading branch information
dedaleDev committed May 25, 2024
1 parent 22b5e6c commit 0d83408
Show file tree
Hide file tree
Showing 46 changed files with 245 additions and 41 deletions.
Binary file added data/livres/1041834365.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2010056426.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2017010090.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2019109964.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070415732.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070450333.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070541290.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070543587.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070556859.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070572676.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070612481.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070615367.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2070624544.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2072847923.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2075085757.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2075094675.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2075120811.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2075126780.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2081211696.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2081230313.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2081244306.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2203020644.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2203020652.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2226249303.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2253014990.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added data/livres/2253093289.jpg
Binary file added data/livres/2266274287.jpg
Binary file added data/livres/2266282395.jpg
Binary file added data/livres/2700238931.jpg
Binary file added data/livres/2700238958.jpg
Binary file added data/livres/2700238974.jpg
Binary file added data/livres/2700256506.jpg
Binary file added data/livres/2747037916.jpg
Binary file added data/livres/2812608935.jpg
Binary file added data/livres/2812619090.jpg
Binary file added data/livres/2812623985.jpg
Binary file added data/livres/2890746623.jpg
Binary file added data/livres/9782070518425.jpg
Binary file added data/livres/9782075090872.jpg
15 changes: 15 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ class db():
"deletePointDeVente" : "DELETE FROM `Point de vente` WHERE `Adresse` = %s;",
"deleteEditeur" : "DELETE FROM `Editeur` WHERE `Nom` = %s;",
"deleteLivreByEditeur" : "DELETE FROM `Livre` WHERE `Editeur` = %s;",
"deleteEmpruntByUser" : "DELETE FROM `Emprunt` WHERE `Utilisateur` = %s;",
"deleteEmprunt" : "DELETE FROM `Emprunt` WHERE `ID` = %s;",
"deleteUser" : "DELETE FROM `Utilisateur` WHERE `email` = %s;",
"updateLivrePointDeVente" : "UPDATE `Livre` SET `Point de vente` = %s WHERE `Point de vente` = %s;",
"updateLivre" : "UPDATE `Livre` SET `Titre` = %s, `Auteur` = %s, `Description` = %s, `Date de parution` = %s, `Statut` = %s, `Genre` = %s, `Format` = %s, `Prix` = %s, `Point de vente` = %s, `Editeur` = %s WHERE `ISBN` = %s;",
"updateAuteur" : "UPDATE `Auteur` SET `Nom` = %s, `Prénom` = %s, `Biographie` = %s, `Date de naissance` = %s, `Date de décès` = %s, `Alias` = %s WHERE `ID` = %s;",
Expand Down Expand Up @@ -74,6 +77,11 @@ def __init__(self, host:str ="localhost", user:str="root", passwd:str="1234", po
self.cursor = self.db.cursor()
self.cursor.execute("DROP DATABASE IF EXISTS BookWorm")
self.db.commit()
try :
for i in os.listdir("www/img/livres"):
os.remove(f"www/img/livres/{i}")
except :
pass
print("Conformément au mode debug, la base de donnée à été effacé au démarrage. Veuillez relancer le programme.")
self.needRestart = True
return
Expand Down Expand Up @@ -211,6 +219,13 @@ def loadData(self) -> int:
0 : if the data is loaded successfully
1 : if an error occurs
"""
try :
print("Importations des images de références...")
for i in os.listdir("data/livres"):
os.system(f"cp data/livres/{i} www/img/livres/{i}")
except Exception as e:
print("Erreur : Impossible d'importer les images de références ! Une erreur est survenue : ",e)

self.db = pymysql.connect(host=self.host, charset="utf8mb4", user=self.user, passwd=self.passwd, port=self.port, db="BookWorm",init_command='SET sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE"')
data= ["data/Auteur.csv","data/Editeur.csv","data/PointDeVente.csv","data/Livre.csv","data/Utilisateur.csv","data/Note.csv","data/Emprunt.csv"]
for file in data:
Expand Down
19 changes: 4 additions & 15 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,10 @@
('Access-Control-Allow-Methods', 'POST, GET'),
('Access-Control-Allow-Headers', 'Content-Type'),
],
},
'/favicon.ico': {
'tools.staticfile.on': True,
'tools.staticfile.filename': os.path.join(www_dir, 'img/favicon.ico')
}
}

Expand Down Expand Up @@ -191,21 +195,6 @@ def updateJS(conf: dict):
if debug :
print("Attention : le mode de débogage est activé, les résultats résultants pourraient être instables.")
db = database.db(db_HOST,db_USER,db_PASSWD,db_PORT,debug)
if debug and not db.needRestart :
try :
db.mkRequest("selectAllISBN", False)
isbn = db.cursor.fetchall()
ISBN = []
for i in isbn :
ISBN.append(i[0])
if ISBN != [] :
for i in os.listdir("www/img/livres"):
if i.split('.')[0] not in ISBN and i.split('.')[1].endswith('jpg') :
print(f"Suppression de {i}", f"www/img/livres/{i}")
os.remove(f"www/img/livres/{i}")
except Exception as e:
print(f"\033[91mErreur : Impossible de supprimer les images inutiles. {e} ligne : {e.__traceback__.tb_lineno}\033[0m")

if db.needRestart == True :
exit(0)
print("Connexion à la base de donnée réussie !")
Expand Down
16 changes: 1 addition & 15 deletions searchEngine.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,21 +155,7 @@ def searchPointDeVente(recherche:str, db:database.db, onlyOne:bool = False)->lis
return None
result = list(temp[0])
if onlyOne and len(result) > 1:
print(f"\nRésultat de la recherche pour {' '.join(recherche)}:\n")
for i in range(len(result)) :
temp = result[i][0].split('\n')
print(f"{i+1} : {temp}, {result[i][1]}")
while True :
try :
saisie = input("Veuillez saisir le numéro du point de vente que vous souhaitez sélectionner : ")
if saisie.isdigit() and int(saisie) >= 1 and int(saisie) <= len(result):
return result[int(saisie)-1]
else:
print("Désolé, le format de la réponse est incorrect. Veuillez réessayer.")
except KeyboardInterrupt:
return None
except :
print("Désolé, le format de la réponse est incorrect. Veuillez réessayer.")
return result[0]
if result == []:
return None
return result
Expand Down
134 changes: 132 additions & 2 deletions server.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ def makeResponse(self, is_error=False, content=None, error_message=None):
return {"status":"error", "message":error_message}
except Exception as e:
print("Erreur lors de la création de la réponse : ",e, e.__traceback__.tb_lineno, content, error_message)

def cleanImageLivres(self) :
"""This function deletes all images who don't have a corresponding book in the database."""
try :
self.db.mkRequest("selectAllISBN", False)
isbn = self.db.cursor.fetchall()
ISBN = []
for i in isbn :
ISBN.append(i[0])
if ISBN != [] :
for i in os.listdir("www/img/livres"):
if i.split('.')[0] not in ISBN and i.split('.')[1].endswith('jpg') :
print(f"Suppression de {i}", f"www/img/livres/{i}")
os.remove(f"www/img/livres/{i}")
except Exception as e:
print("\033[31mErreur lors de la suppression des images : ",e, e.__traceback__.tb_lineno, "\033[0m")

@cherrypy.expose()
@cherrypy.tools.json_out()
Expand Down Expand Up @@ -156,6 +172,10 @@ def deleteLivre(self, email:str, password:str, isbn:str) -> str:
self.db.mkRequest("deleteEmpruntByISBN", False, isbn)
self.db.mkRequest("deleteLivre", False, isbn)
self.db.db.commit()
try :
os.remove(f"www/img/livres/{isbn}.jpg")
except Exception as e:
print("\033[31mErreur lors de la suppression de l'image : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Vous n'êtes pas administrateur")
Expand All @@ -176,12 +196,11 @@ def deleteAuteur(self, email:str, password:str, id:int) -> str:
if user is not None and user != () and user != []:
if user[0][1] == password:
if user[0][2] == "admin":
print("ID DELECTION READY",id)
self.db.mkRequest("deleteEmpruntByAuteurID", False, id)
self.db.mkRequest("deleteLivreByAuteur", False, id)#delete all books from this author first
self.db.mkRequest("deleteAuteur", False, id)
print("OK")
self.db.db.commit()
self.cleanImageLivres()
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Vous n'êtes pas administrateur")
Expand All @@ -193,6 +212,117 @@ def deleteAuteur(self, email:str, password:str, id:int) -> str:
print("\033[31mErreur lors de la suppression de l'auteur : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def getPointDeVenteReplacement(self, replacementName):
try :
replacementPointDeVente = searchEngine.searchPointDeVente(replacementName, self.db, onlyOne=True)
if replacementPointDeVente == None:
return self.makeResponse(is_error=True, error_message="Point de vente de remplacement introuvable")
print("POINT DE VENTE REMPLACEMENT",replacementPointDeVente)
return self.makeResponse(content=replacementPointDeVente[0][0])
except Exception as e:
print("\033[31mErreur lors de la recherche du point de vente de remplacement : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def deletePointDeVente(self, email:str, password:str, adresse:str, adresseReplacement: str) -> str:
try :
self.db.mkRequest("selectUserByEmail", False, email)
user = self.db.cursor.fetchall()
if user is not None and user != () and user != []:
if user[0][1] == password:
if user[0][2] == "admin":
print("ADRESSE REPLACEMENT",adresseReplacement)
print("ADRESSE",adresse)
self.db.mkRequest("updateLivrePointDeVente", False, operationOnDataBase.convertPointDeVenteToAcceptablePointDeVente(adresseReplacement,self.db), operationOnDataBase.convertPointDeVenteToAcceptablePointDeVente(adresse,self.db))
self.db.mkRequest("deletePointDeVente", False, operationOnDataBase.convertPointDeVenteToAcceptablePointDeVente(adresse,self.db))
self.db.db.commit()
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Vous n'êtes pas administrateur")
else:
return self.makeResponse(is_error=True, error_message="Mot de passe incorrect")
else:
return self.makeResponse(is_error=True, error_message="Utilisateur introuvable")
except Exception as e:
print("\033[31mErreur lors de la suppression du point de vente : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def deleteEditeur(self, email:str, password:str, nom:str) -> str:
try :
self.db.mkRequest("selectUserByEmail", False, email)
user = self.db.cursor.fetchall()
if user is not None and user != () and user != []:
if user[0][1] == password:
if user[0][2] == "admin":
self.db.mkRequest("deleteLivreByEditeur", False, nom)#delete all books from this editor first
self.db.mkRequest("deleteEditeur", False, nom)
self.db.db.commit()
self.cleanImageLivres()
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Vous n'êtes pas administrateur")
else:
return self.makeResponse(is_error=True, error_message="Mot de passe incorrect")
else:
return self.makeResponse(is_error=True, error_message="Utilisateur introuvable")
except Exception as e:
print("\033[31mErreur lors de la suppression de l'éditeur : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def deleteUser(self, email:str, password:str, emailToDelete:str) -> str:
print("EMAIL",email, "PASSWORD",password, "EMAIL TO DELETE",emailToDelete)
try :
self.db.mkRequest("selectUserByEmail", False, email)
user = self.db.cursor.fetchall()
if user is not None and user != () and user != []:
if user[0][1] == password:
if user[0][2] == "admin":
#check if the user to delete is admin, if so, refuse
self.db.mkRequest("selectUserByEmail", False, emailToDelete)
userToDelete = self.db.cursor.fetchall()
if userToDelete is not None and userToDelete != () and userToDelete != []:
if userToDelete[0][2] == "admin":
return self.makeResponse(is_error=True, error_message="Vous ne pouvez pas supprimer un administrateur")
self.db.mkRequest("deleteEmpruntByUser", False, emailToDelete)
self.db.mkRequest("deleteUser", False, emailToDelete)
self.db.db.commit()
print("OK")
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Vous n'êtes pas administrateur")
else:
return self.makeResponse(is_error=True, error_message="Mot de passe incorrect")
else:
return self.makeResponse(is_error=True, error_message="Utilisateur introuvable")
except Exception as e:
print("\033[31mErreur lors de la suppression de l'utilisateur : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
def deleteEmprunt(self, email:str, password:str, id:int) -> str:
try :
self.db.mkRequest("selectUserByEmail", False, email)
user = self.db.cursor.fetchall()
if user is not None and user != () and user != []:
if user[0][1] == password:
self.db.mkRequest("deleteEmprunt", False, id)
self.db.db.commit()
return self.makeResponse(content="success")
else:
return self.makeResponse(is_error=True, error_message="Mot de passe incorrect")
else:
return self.makeResponse(is_error=True, error_message="Utilisateur introuvable")
except Exception as e:
print("\033[31mErreur lors de la suppression de l'emprunt : ",e, e.__traceback__.tb_lineno, "\033[0m")
return self.makeResponse(is_error=True, error_message="Oups, une erreur est survenue, veuillez réessayer ultérieurement")

@cherrypy.expose
@cherrypy.tools.json_out()
Expand Down
7 changes: 6 additions & 1 deletion test.py
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
Modified 2 , Rowling==Rowling , Joanne==Joanne , J. K. Rowling==J. K. Rowling , Joanne Rowling [ d͡ʒoʊˈæn ˈroʊlɪŋ]a, plus connue sous les noms de plume J. K. Rowlingb et Robert Galbraith, est une romancière et scénariste britannique née le 31 juillet 1965 dans lagglomération de Yate (Gloucestershire du Sud). Elle doit sa notoriété mondiale à la série Harry Potter, dont les romans traduits en près de quatre-vingts langues ont été vendus à plus de 500 millions d'exemplaires dans le monde.==Joanne Rowling [ d͡ʒoʊˈæn ˈroʊlɪŋ]a, plus connue sous les noms de plume J. K. Rowlingb et Robert Galbraith, est une romancière et scénariste britannique née le 31 juillet 1965 dans l’agglomération de Yate (Gloucestershire du Sud). Elle doit sa notoriété mondiale à la série Harry Potter, dont les romans traduits en près de quatre-vingts langues ont été vendus à plus de 500 millions d'exemplaires dans le monde. , 1965-07-31==31/07/1965 , null==null
ADRESSE REPLACEMENT Place Charles de Gaulle à Chabeuil (Drôme)
ADRESSE 17, avenue Victor-Hugo Centre commercial Victor-Hugo - 26000 Valence
point de vente non trouvé 17,avenueVictor-HugoCentrecommercialVictor-Hugo-26000Valence!=PlaceCharlesdeGaulleàChabeuil(Drôme)
point de vente non trouvé 31rueMadierdeMontjau26000Valence!=PlaceCharlesdeGaulleàChabeuil(Drôme)
point de vente trouvé Place Charles de Gaulle à Chabeuil (Drôme)
point de vente trouvé 17, avenue Victor-Hugo Centre commercial Victor-Hugo - 26000 Valence
Binary file added www/img/favicon.ico
Binary file not shown.
Loading

0 comments on commit 0d83408

Please sign in to comment.