All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
231 lines
6.7 KiB
Python
231 lines
6.7 KiB
Python
from flask import Flask, request, render_template, jsonify, redirect, url_for, g
|
|
import sqlite3
|
|
from flask_oidc import OpenIDConnect
|
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
|
import os
|
|
import json
|
|
import psycopg2
|
|
import logging
|
|
from math import ceil, floor
|
|
|
|
app = Flask(__name__)
|
|
app.config.update({
|
|
'SECRET_KEY': os.environ['SECRET'],
|
|
'DEBUG': False,
|
|
'OIDC_CLIENT_SECRETS': json.loads(os.environ['CLIENT_SECRETS']),
|
|
'OIDC_ID_TOKEN_COOKIE_SECURE': False,
|
|
'OIDC_USER_INFO_ENABLED': True,
|
|
'OIDC_OPENID_REALM': 'hottis',
|
|
'OIDC_SCOPES': ['openid', 'email', 'profile']
|
|
})
|
|
|
|
oidc = OpenIDConnect(app)
|
|
app.logger.handlers = logging.getLogger('gunicorn.error').handlers
|
|
|
|
datapw = 'dasrtwegdffgtewrt4335wferg'
|
|
|
|
def calculate_nutrition(food, weight):
|
|
try:
|
|
conn = psycopg2.connect()
|
|
|
|
with conn.cursor() as cursor:
|
|
# Abfrage der Nährwertdaten aus der Datenbank
|
|
cursor.execute('SELECT kcal, EW, Fett, KH, BST, CA FROM nutrition_table WHERE name = %s', (food,))
|
|
|
|
result = cursor.fetchone()
|
|
|
|
if result:
|
|
# Runden und Berechnen der Nährwerte basierend auf dem Gewicht
|
|
kcal, ew, fett, kh, bst, ca = result
|
|
nutrition_values = [
|
|
schulrunden(kcal * weight / 100, ist_kcal=True), # kcal gerundet auf ganze Zahl
|
|
schulrunden(ew * weight / 100, 1), # EW gerundet auf eine Dezimalstelle
|
|
schulrunden(fett * weight / 100, 1), # Fett gerundet auf eine Dezimalstelle
|
|
schulrunden(kh * weight / 100, 1), # KH gerundet auf eine Dezimalstelle
|
|
schulrunden(bst * weight / 100, 1), # BST gerundet auf eine Dezimalstelle
|
|
schulrunden(ca * weight / 100) # CA gerundet auf ganze Zahl
|
|
]
|
|
return nutrition_values
|
|
else:
|
|
return None
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
|
|
|
|
def schulrunden(zahl, stellen=0, ist_kcal=False):
|
|
# Wenn es sich um kcal handelt und der Wert vor der Rundung zwischen 0 und 1 liegt
|
|
if ist_kcal and 0 < zahl < 1:
|
|
return 1
|
|
|
|
faktor = 10 ** stellen
|
|
zahl = zahl * faktor
|
|
basis = floor(zahl)
|
|
if zahl - basis >= 0.5:
|
|
gerundet = basis + 1
|
|
else:
|
|
gerundet = basis
|
|
return gerundet / faktor
|
|
|
|
|
|
|
|
# Index-Route
|
|
@app.route('/')
|
|
@oidc.require_login
|
|
def index():
|
|
return render_template('index.html')
|
|
|
|
# ...
|
|
|
|
@app.route('/get_products')
|
|
# @oidc.require_login
|
|
def get_products():
|
|
try:
|
|
conn = psycopg2.connect()
|
|
with conn.cursor() as cursor:
|
|
cursor.execute('SELECT name FROM nutrition_table ORDER BY name')
|
|
products = cursor.fetchall()
|
|
return {'products': [product[0] for product in products]}
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
# Route zum Hinzufügen und Berechnen von Lebensmitteln
|
|
@app.route('/add_lm', methods=['GET'])
|
|
# @oidc.require_login
|
|
def add_lm():
|
|
food = request.args.get('food')
|
|
weight = float(request.args.get('weight'))
|
|
|
|
nutrition = calculate_nutrition(food, weight)
|
|
if nutrition:
|
|
# Extrahieren der einzelnen Nährwerte
|
|
kcal, ew, fett, kh, bst, ca = nutrition
|
|
return jsonify({
|
|
"food": food,
|
|
"kcal": kcal,
|
|
"ew": ew,
|
|
"fett": fett,
|
|
"kh": kh,
|
|
"bst": bst,
|
|
"ca": ca
|
|
})
|
|
else:
|
|
return "Lebensmittel nicht gefunden.", 404
|
|
|
|
|
|
def convert_decimal(value):
|
|
try:
|
|
return float(value.replace(',', '.'))
|
|
except (ValueError, TypeError):
|
|
return 0.0 # Rückgabe eines Standardwertes im Fehlerfall
|
|
|
|
|
|
@app.route('/add_nutrition', methods=['POST'])
|
|
# @oidc.accept_token(['openid'])
|
|
def add_nutrition():
|
|
app.logger.info("add_nutrition")
|
|
|
|
food = request.form.get('food')
|
|
kcal = convert_decimal(request.form.get('kcal'))
|
|
ew = convert_decimal(request.form.get('ew'))
|
|
fett = convert_decimal(request.form.get('fett'))
|
|
kh = convert_decimal(request.form.get('kh'))
|
|
bst = convert_decimal(request.form.get('bst'))
|
|
ca = convert_decimal(request.form.get('ca'))
|
|
|
|
# Verbindung zur Datenbank herstellen und Daten einfügen
|
|
try:
|
|
conn = psycopg2.connect()
|
|
with conn.cursor() as cursor:
|
|
cursor.execute("INSERT INTO nutrition_table (name, kcal, ew, fett, kh, bst, ca) VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
|
(food, kcal, ew, fett, kh, bst, ca))
|
|
conn.commit()
|
|
|
|
return redirect(url_for('nutrition'))
|
|
except Exception as e:
|
|
app.logger.warn(f"error in add_nutrition: {e}")
|
|
return jsonify({"error": str(e)}), 500
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
@app.route('/nutrition')
|
|
# @oidc.require_login
|
|
def nutrition():
|
|
return render_template('nutrition.html')
|
|
|
|
@app.route('/get_token')
|
|
# @oidc.require_login
|
|
def get_token():
|
|
return jsonify(token=oidc.get_access_token())
|
|
|
|
|
|
@app.route('/get_database_entries')
|
|
# @oidc.require_login
|
|
def get_database_entries():
|
|
try:
|
|
# Ersetzen Sie diese Werte mit Ihren Datenbank-Verbindungsinformationen
|
|
conn = psycopg2.connect()
|
|
cursor = conn.cursor()
|
|
with conn.cursor() as cursor:
|
|
cursor.execute("SELECT name, kcal, ew, fett, kh, bst, ca FROM nutrition_table ORDER BY name")
|
|
entries = cursor.fetchall()
|
|
|
|
# Umwandeln der Daten in ein JSON-freundliches Format
|
|
entries_list = []
|
|
for entry in entries:
|
|
entries_list.append({
|
|
"food": entry[0],
|
|
"kcal": entry[1],
|
|
"ew": entry[2],
|
|
"fett": entry[3],
|
|
"kh": entry[4],
|
|
"bst": entry[5],
|
|
"ca": entry[6]
|
|
})
|
|
return jsonify(entries_list)
|
|
except Exception as e:
|
|
return jsonify({"error": str(e)}), 500
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
@app.route('/delete_nutrition', methods=['POST'])
|
|
# @oidc.accept_token(['openid'])
|
|
def delete_nutrition():
|
|
data = request.get_json()
|
|
foodNames = data['foodNames']
|
|
|
|
if not foodNames:
|
|
return jsonify({'error': 'Keine Lebensmittel zum Löschen angegeben'}), 400
|
|
|
|
try:
|
|
conn = psycopg2.connect()
|
|
with conn.cursor() as cursor:
|
|
query = "DELETE FROM nutrition_table WHERE name = ANY(%s)"
|
|
cursor.execute(query, (foodNames,))
|
|
conn.commit()
|
|
return jsonify({'message': 'Erfolgreich gelöscht'}), 200
|
|
except Exception as e:
|
|
return jsonify({'error': str(e)}), 500
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
@app.route('/random')
|
|
def random_page():
|
|
# Diese Route gibt die HTML-Seite 'random.html' zurück
|
|
return render_template('random.html')
|
|
|
|
|
|
exposed_app = ProxyFix(app, x_for=1, x_host=1)
|
|
|
|
#
|