Refactoring

This commit is contained in:
2024-06-02 19:03:00 +02:00
parent 57b5b4ffab
commit 8c11166397
14 changed files with 401 additions and 322 deletions

View File

@ -2,7 +2,7 @@ import json
import asyncio
from init import db, Meals, scheduler, flask_app
from init import db, Meals, scheduler, flaskApp
import datetime
import time
import httpx
@ -41,36 +41,37 @@ async def getMealsFromAPI(day: str, dbentry: bool = False):
async with httpx.AsyncClient() as s:
response = await s.get(url=f"https://dh-api.paulmartin.cloud/plans/{day}?canteens=erzberger")
response = response.content
jres = json.loads(response.decode("utf-8"))
jsonResponse = json.loads(response.decode("utf-8"))
essen = []
try:
num = len(jres["data"][0]["lines"])
for i in range(num):
number = len(jsonResponse["data"][0]["lines"])
for i in range(number):
try:
jsmeal = jres["data"][0]["lines"][i]["meals"]
cont = True
jsonMeals = jsonResponse["data"][0]["lines"][i]["meals"]
hasContent = True
except IndexError:
essen = []
cont = False
if cont:
for e in range(len(jsmeal)):
ji = jsmeal[e]
name = ji["name"]
if pricetofloat(ji["price"]) >= 1.1:
vegan = ji["classifiers"].count("VG") == 1
schwein = ji["classifiers"].count("S") == 1
hasContent = False
if hasContent:
for e in range(len(jsonMeals)):
jsonEntry = jsonMeals[e]
name = jsonEntry["name"]
if pricetofloat(jsonEntry["price"]) >= 1.1:
vegan = jsonEntry["classifiers"].count("VG") == 1
schwein = jsonEntry["classifiers"].count("S") == 1
if vegan:
veget = True
vegetarian = True
else:
veget = ji["classifiers"].count("VEG") == 1
if veget:
vegetarian = jsonEntry["classifiers"].count("VEG") == 1
if vegetarian:
if name.count("Reibekäse") > 0:
vegan = True
essen += [name]
if dbentry:
mid = int(time.time() * 1000) % 100000
neu = Meals(date=day, name=name, id=mid, vegan=vegan, vegetarian=veget, schwein=schwein)
neu = Meals(date=day, name=name, id=mid, vegan=vegan, vegetarian=vegetarian,
schwein=schwein)
db.session.add(neu)
db.session.commit()
if not essen:
@ -102,20 +103,20 @@ def formatDay(day: datetime):
:return str:
"""
if day.month < 10:
mon = "0" + str(day.month)
monat = "0" + str(day.month)
else:
mon = str(day.month)
monat = str(day.month)
if day.day < 10:
tag = "0" + str(day.day)
else:
tag = str(day.day)
day = str(day.year) + "-" + mon + "-" + tag
return day
formattedDay = str(day.year) + "-" + monat + "-" + tag
return formattedDay
async def refreshMeals():
"""
Aktualisiert immer vormittags alle Mahlzeiten in der Datenbank. \n
Aktualisiert alle Mahlzeiten in der Datenbank. \n
Datenbankeinträge werden ersetzt, wenn die API andere Mahlzeiten liefert.
"""
print("Aktualisiere Essenspläne...\n")
@ -128,20 +129,22 @@ async def refreshMeals():
for i in range(len(dates)):
dates[i] = formatDay(dates[i])
for i in dates:
apinames = await getMealsFromAPI(i)
apinames = await getMealsFromAPI(i)
dbmeals = Meals.query.filter_by(date=i).all()
dbnames = []
for m in dbmeals:
dbnames += [m.name]
if set(dbnames) != set(apinames) and nomeal not in apinames:
for n in dbnames:
db.session.delete(Meals.query.filter_by(date=i, name=n).first())
apiNames = await getMealsFromAPI(i)
dbMeals = Meals.query.filter_by(date=i).all()
dbNames = []
for meal in dbMeals:
dbNames += [meal.name]
if set(dbNames) != set(apiNames) and nomeal not in apiNames:
for name in dbNames:
db.session.delete(Meals.query.filter_by(date=i, name=name).first())
db.session.commit()
await getMealsFromAPI(i, True)
@scheduler.task('cron', id="mensaschedule", hour='8-11', day_of_week='*', minute='*/15', week='*', second='5')
def mensaschedule():
with flask_app.app_context():
@scheduler.task('cron', id="mensaSchedule", hour='8-11', day_of_week='*', minute='*/15', week='*', second='5')
def mensaSchedule():
"""
Nutzt vormittags die Funktion refreshMeals(), um die Essen zu aktualisieren
"""
with flaskApp.app_context():
asyncio.run(refreshMeals())