183 lines
5.4 KiB
Python
183 lines
5.4 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
|
|
|
|
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
|
|
|
|
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 = [
|
|
round(kcal * weight / 100), # kcal gerundet auf ganze Zahl
|
|
round(ew * weight / 100, 1), # EW gerundet auf eine Dezimalstelle
|
|
round(fett * weight / 100, 1), # Fett gerundet auf eine Dezimalstelle
|
|
round(kh * weight / 100, 1), # KH gerundet auf eine Dezimalstelle
|
|
round(bst * weight / 100, 1), # BST gerundet auf eine Dezimalstelle
|
|
round(ca * weight / 100) # CA gerundet auf ganze Zahl
|
|
]
|
|
return nutrition_values
|
|
else:
|
|
return None
|
|
finally:
|
|
if conn:
|
|
conn.close()
|
|
|
|
|
|
|
|
# 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')
|
|
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()
|
|
|
|
exposed_app = ProxyFix(app, x_for=1, x_host=1)
|
|
|
|
|
|
|
|
|