improved logging; improved error handeling; made FIP entrys delete
This commit is contained in:
Binary file not shown.
99
app/main.py
99
app/main.py
@@ -37,19 +37,20 @@ debug = log.debug
|
|||||||
info = log.info
|
info = log.info
|
||||||
error = log.error
|
error = log.error
|
||||||
|
|
||||||
|
|
||||||
def startup():
|
|
||||||
info("App Started")
|
|
||||||
|
|
||||||
|
|
||||||
startup()
|
|
||||||
app = FastAPI()
|
|
||||||
|
|
||||||
app.mount("/favicon", StaticFiles(directory="./favicon"), name="favicon")
|
|
||||||
app.mount("/static", StaticFiles(directory="./static"), name="static")
|
|
||||||
db = mariadb.connect(
|
db = mariadb.connect(
|
||||||
host="localhost", user="wildserver", password="DBPassword", database="Unizeug"
|
host="localhost", user="wildserver", password="DBPassword", database="Unizeug"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
info("App Started")
|
||||||
|
# remove_old_FIP_entrys()
|
||||||
|
|
||||||
|
|
||||||
|
# startup()
|
||||||
|
app = FastAPI()
|
||||||
|
app.mount("/favicon", StaticFiles(directory="./favicon"), name="favicon")
|
||||||
|
app.mount("/static", StaticFiles(directory="./static"), name="static")
|
||||||
|
|
||||||
|
|
||||||
CATEGORIES = [
|
CATEGORIES = [
|
||||||
"Prüfungen",
|
"Prüfungen",
|
||||||
"Klausuren",
|
"Klausuren",
|
||||||
@@ -81,7 +82,8 @@ def _sql_quarry(
|
|||||||
cursor: mariadb.Cursor,
|
cursor: mariadb.Cursor,
|
||||||
querry: str,
|
querry: str,
|
||||||
data: Tuple[str | int, ...] | int | str,
|
data: Tuple[str | int, ...] | int | str,
|
||||||
return_result,
|
return_result: bool,
|
||||||
|
commit: bool,
|
||||||
) -> List:
|
) -> List:
|
||||||
datas: Tuple[str | int, ...]
|
datas: Tuple[str | int, ...]
|
||||||
if type(data) is str or type(data) is int:
|
if type(data) is str or type(data) is int:
|
||||||
@@ -90,29 +92,37 @@ def _sql_quarry(
|
|||||||
datas = data
|
datas = data
|
||||||
try:
|
try:
|
||||||
cursor.execute(querry, datas)
|
cursor.execute(querry, datas)
|
||||||
|
if commit:
|
||||||
|
db.commit()
|
||||||
if return_result:
|
if return_result:
|
||||||
return cursor.fetchall()
|
return cursor.fetchall()
|
||||||
else:
|
else:
|
||||||
return []
|
return []
|
||||||
except mariadb.Error as e:
|
except mariadb.Error as e:
|
||||||
error(f"Mariadb Error: {e}")
|
error(f"Mariadb Error: '{e}' from Querry: '{querry}' with variables: {data}")
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=500, detail="Somethings wrong with the database"
|
status_code=500, detail="Somethings wrong with the database"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def sql(
|
def sql(
|
||||||
querry: str, data: Tuple[str | int, ...] | str | int, return_result: bool = True
|
querry: str,
|
||||||
|
data: Tuple[str | int, ...] | str | int = (),
|
||||||
|
return_result: bool = True,
|
||||||
|
commit: bool = False,
|
||||||
) -> List[Tuple]:
|
) -> List[Tuple]:
|
||||||
cur = db.cursor(dictionary=False)
|
cur = db.cursor(dictionary=False)
|
||||||
return _sql_quarry(cur, querry, data, return_result)
|
return _sql_quarry(cur, querry, data, return_result, commit)
|
||||||
|
|
||||||
|
|
||||||
def sqlT(
|
def sqlT(
|
||||||
querry: str, data: tuple[str | int, ...] | str | int, return_result: bool = True
|
querry: str,
|
||||||
|
data: tuple[str | int, ...] | str | int = (),
|
||||||
|
return_result: bool = True,
|
||||||
|
commit: bool = False,
|
||||||
) -> List[Dict]:
|
) -> List[Dict]:
|
||||||
cur = db.cursor(dictionary=True)
|
cur = db.cursor(dictionary=True)
|
||||||
return _sql_quarry(cur, querry, data, return_result)
|
return _sql_quarry(cur, querry, data, return_result, commit)
|
||||||
|
|
||||||
# datas:Tuple[str|int,...]
|
# datas:Tuple[str|int,...]
|
||||||
# if type(data) is str or type(data) is int:
|
# if type(data) is str or type(data) is int:
|
||||||
@@ -340,8 +350,8 @@ async def create_upload_file(files: List[UploadFile], c2pdf: bool = True):
|
|||||||
# cur = db.cursor()
|
# cur = db.cursor()
|
||||||
# try:
|
# try:
|
||||||
sql(
|
sql(
|
||||||
"INSERT INTO FIP (filename,filetype,initTimeStamp) Values(?,?,?)",
|
"INSERT INTO FIP (filename,filetype,initTimeStamp) Values(?,?,NOW())",
|
||||||
(filename, ft, str(datetime.datetime.now())),
|
(filename, ft), # str(datetime.datetime.now())
|
||||||
return_result=False,
|
return_result=False,
|
||||||
)
|
)
|
||||||
# except mariadb.Error as e:
|
# except mariadb.Error as e:
|
||||||
@@ -411,7 +421,14 @@ async def get_submission(
|
|||||||
res = sql("Select filename from FIP where id=?", (fileId,))
|
res = sql("Select filename from FIP where id=?", (fileId,))
|
||||||
if len(res) < 1:
|
if len(res) < 1:
|
||||||
error(f"Submited file ID {fileId} dose not exist in database")
|
error(f"Submited file ID {fileId} dose not exist in database")
|
||||||
|
if fileId == "greeting":
|
||||||
|
raise HTTPException(400, "You need to upload a file before submitting")
|
||||||
raise HTTPException(status_code=400, detail="Submited file dose not exist.")
|
raise HTTPException(status_code=400, detail="Submited file dose not exist.")
|
||||||
|
for th in [(lva, "LVA"), (prof, "Prof"), (fname, "Filename"), (sem, "Semmester")]:
|
||||||
|
if th[0] == "":
|
||||||
|
error(f"User tried to upload a file without specifying the {th[1]}")
|
||||||
|
raise HTTPException(400, f"You need to specify a {th[1]}")
|
||||||
|
|
||||||
filepath = "./app/files/" + res[0][0]
|
filepath = "./app/files/" + res[0][0]
|
||||||
# except mariadb.Error as e:
|
# except mariadb.Error as e:
|
||||||
# print(f"Mariadb Error: {e}")
|
# print(f"Mariadb Error: {e}")
|
||||||
@@ -422,13 +439,15 @@ async def get_submission(
|
|||||||
try:
|
try:
|
||||||
dest = make_savepath(lva, prof, stype, subcat, sem, ex_date, fname, ftype)
|
dest = make_savepath(lva, prof, stype, subcat, sem, ex_date, fname, ftype)
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
error(f"Error creating savepath: f{e}")
|
error(f"Error creating savepath: {e}")
|
||||||
raise HTTPException(status_code=400, detail="Cannot create Savepath")
|
raise HTTPException(status_code=400, detail=f"Error creation savepath: {e}")
|
||||||
await censor_pdf(
|
await censor_pdf(
|
||||||
filepath, dest, rects_p, scales_p, False if censor == "False" else True
|
filepath, dest, rects_p, scales_p, False if censor == "False" else True
|
||||||
)
|
)
|
||||||
# return {"done": "ok"}
|
# return {"done": "ok"}
|
||||||
print(dest)
|
# print(dest)
|
||||||
|
info(f"Saved file {fileId} as {dest}")
|
||||||
|
delete_from_FIP(fileId)
|
||||||
return FileResponse(dest, content_disposition_type="inline")
|
return FileResponse(dest, content_disposition_type="inline")
|
||||||
|
|
||||||
|
|
||||||
@@ -578,8 +597,17 @@ def make_savepath(
|
|||||||
os.makedirs(savepath, exist_ok=True)
|
os.makedirs(savepath, exist_ok=True)
|
||||||
filename = sem + "_"
|
filename = sem + "_"
|
||||||
if int(cat) in EX_DATE_CATEGORIES_I:
|
if int(cat) in EX_DATE_CATEGORIES_I:
|
||||||
_, mm, dd = ex_date.split("-")
|
try:
|
||||||
filename += mm + "_" + dd + "_"
|
yyyy, mm, dd = ex_date.split("-")
|
||||||
|
except ValueError as e:
|
||||||
|
error(
|
||||||
|
f"ValueError: f{e}. Probably caused by user not specifying a date where a date is required"
|
||||||
|
)
|
||||||
|
raise HTTPException(
|
||||||
|
400,
|
||||||
|
"You have not specified a date for an upload that requires a date like an exam.",
|
||||||
|
)
|
||||||
|
filename += yyyy + "_" + mm + "_" + dd + "_"
|
||||||
filename += fname + "." + ftype
|
filename += fname + "." + ftype
|
||||||
return savepath + filename
|
return savepath + filename
|
||||||
|
|
||||||
@@ -795,3 +823,28 @@ def guess_filetype(content: bytes, filename: str) -> str:
|
|||||||
if len(farr) > 1:
|
if len(farr) > 1:
|
||||||
return filename.split(".")[-1]
|
return filename.split(".")[-1]
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/remove_old")
|
||||||
|
async def remove_old_FIP_entrys():
|
||||||
|
files = sqlT(
|
||||||
|
"SELECT id,filename FROM FIP WHERE HOUR(TIMEDIFF(NOW(),initTimeStamp)) > 24 "
|
||||||
|
)
|
||||||
|
info(f"Remove Files: {files}")
|
||||||
|
for file in files:
|
||||||
|
sql("DELETE FROM FIP WHERE id=?", (file["id"]), return_result=False)
|
||||||
|
os.remove(FILES_IN_PROGRESS + file["filename"])
|
||||||
|
# sql(
|
||||||
|
# "DELETE FROM FIP WHERE HOUR(TIMEDIFF(NOW(),initTimeStamp)) > 24",
|
||||||
|
# return_result=False,
|
||||||
|
# )
|
||||||
|
db.commit()
|
||||||
|
return FileResponse("./index.html")
|
||||||
|
|
||||||
|
|
||||||
|
def delete_from_FIP(uuid: str):
|
||||||
|
res = sqlT("SELECT filename FROM FIP WHERE id=?", (uuid,))
|
||||||
|
if len(res) < 1:
|
||||||
|
raise HTTPException(500, "I am trying to delete a file that dose not exist")
|
||||||
|
sql("DELETE FROM FIP WHERE id=?", (uuid,), return_result=False, commit=True)
|
||||||
|
os.remove(FILES_IN_PROGRESS + res[0]["filename"])
|
||||||
|
|||||||
@@ -288,6 +288,7 @@ async function submitForm(formData) {
|
|||||||
//let responseJSON=await response.json();
|
//let responseJSON=await response.json();
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
console.log("Submit OK");
|
console.log("Submit OK");
|
||||||
|
doc = new PDFDocument("./files/greeting", "greeting", "pdf");
|
||||||
// console.log(response);
|
// console.log(response);
|
||||||
// window.open(response);
|
// window.open(response);
|
||||||
// console.log(URL.createObjectURL(response.body));
|
// console.log(URL.createObjectURL(response.body));
|
||||||
@@ -300,6 +301,7 @@ async function submitForm(formData) {
|
|||||||
window.open(blobURL, "_blank");
|
window.open(blobURL, "_blank");
|
||||||
} else {
|
} else {
|
||||||
console.log("Submit failed");
|
console.log("Submit failed");
|
||||||
|
window.alert("Error: " + (await response.json())["detail"]);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error" + error);
|
console.error("Error" + error);
|
||||||
@@ -339,6 +341,7 @@ async function uploadFile(formData) {
|
|||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log("upload failed");
|
console.log("upload failed");
|
||||||
|
window.alert("Error: " + (await response.json())["detail"]);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error("Error: " + error);
|
console.error("Error: " + error);
|
||||||
|
|||||||
@@ -8,7 +8,11 @@ function autocomplete(inp, type) {
|
|||||||
the text field element and an array of possible autocompleted values:*/
|
the text field element and an array of possible autocompleted values:*/
|
||||||
var currentFocus;
|
var currentFocus;
|
||||||
/*execute a function when someone writes in the text field:*/
|
/*execute a function when someone writes in the text field:*/
|
||||||
inp.addEventListener("focus", updateAutocomplete);
|
inp.addEventListener("focus", (e) => {
|
||||||
|
e.target.select();
|
||||||
|
// this.select();
|
||||||
|
updateAutocomplete();
|
||||||
|
});
|
||||||
inp.addEventListener("input", updateAutocomplete);
|
inp.addEventListener("input", updateAutocomplete);
|
||||||
async function updateAutocomplete() {
|
async function updateAutocomplete() {
|
||||||
activeAutocompletion = type;
|
activeAutocompletion = type;
|
||||||
|
|||||||
Reference in New Issue
Block a user