Add barcode scanning and nutrition lookup feature

Introduces a new /scan route and template for barcode scanning using ZXing in the browser. Adds a /nutri/<barcode> API endpoint to fetch food item nutrition data by barcode. Updates the FoodItem model to include a barcode field and a to_dict method for JSON serialization. Also updates seed data to include a barcode.
This commit is contained in:
2025-06-29 00:08:25 +02:00
parent d5e8c3fa94
commit 0919048cfd
4 changed files with 148 additions and 6 deletions

25
app.py
View File

@@ -1,4 +1,4 @@
from flask import render_template, redirect, url_for
from flask import render_template, redirect, url_for, request, jsonify
from flask_login import (
login_required,
logout_user,
@@ -6,7 +6,7 @@ from flask_login import (
current_user,
)
from forms import LoginForm
from models import User
from models import User, FoodItem
from application import db, app, login_manager
from application.admin.routes import admin_bp
@@ -43,8 +43,9 @@ def login():
user = User.query.filter_by(username=form.username.data).first()
if user and user.check_password(password=form.password.data):
# User found and password correct
login_user(user)
return redirect(url_for("dashboard"))
next_page = request.args.get("next") # Get next page if given
login_user(user) # Log in the user
return redirect(next_page or url_for("dashboard"))
else:
pass
# invalid user
@@ -64,6 +65,22 @@ def logout():
return redirect(url_for("index"))
@app.route("/scan")
@login_required
def scan():
return render_template("scan.html")
@app.route("/nutri/<int:barcode>", methods=["GET"])
@login_required
def nutri(barcode):
food = FoodItem.query.filter_by(barcode=barcode).first()
if food:
return jsonify(food.to_dict())
else:
return jsonify({})
# Run
if __name__ == "__main__":