-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoints.py
More file actions
71 lines (52 loc) · 2.58 KB
/
endpoints.py
File metadata and controls
71 lines (52 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from flask import Flask, jsonify
import json
import urllib.parse
app = Flask(__name__)
with open("mcdonalds_menu_data.json", "r", encoding="utf-8") as f:
data = json.load(f)
def normalize(s):
return s.lower().replace('"', '').strip()
@app.route("/all_products/", methods=["GET"])
def get_all_products():
return jsonify(data)
@app.route("/all_products/<product_name>", methods=["GET"])
def search_products(product_name):
decoded = urllib.parse.unquote(product_name)
norm = normalize(decoded)
matched = {k: v for k, v in data.items() if norm in normalize(k)}
if not matched:
return jsonify({"error": "Продукт не знайдено"}), 404
if len(matched) == 1:
# Якщо один збіг — повертаємо повну інформацію про продукт
return jsonify(next(iter(matched.values())))
# Якщо кілька збігів — повертаємо тільки назви продуктів
return jsonify({"matches": list(matched.keys())})
@app.route("/all_products/<product_name>/<product_field>", methods=["GET"])
def get_product_field(product_name, product_field):
decoded_name = urllib.parse.unquote(product_name)
decoded_field = urllib.parse.unquote(product_field)
norm_name = normalize(decoded_name)
norm_field = normalize(decoded_field)
# Частковий збіг по назві продукту (v - value, k - key)
matched = {k: v for k, v in data.items() if norm_name in normalize(k)}
if not matched:
return jsonify({"error": "Продукт не знайдено"}), 404
if len(matched) > 1:
return jsonify({
"error": "Знайдено кілька продуктів, уточніть назву",
"matches": list(matched.keys())
}), 400
product = next(iter(matched.values()))
nutrients = product.get("нутрієнти", {})
if not nutrients:
return jsonify({"error": "Немає інформації про нутрієнти"}), 404
# Точний збіг по назві поля всередині нутрієнтів
for field_key, field_val in nutrients.items():
if normalize(field_key) == norm_field:
return jsonify({field_key: field_val})
return jsonify({
"error": f"Поле '{decoded_field}' не знайдено у нутрієнтах продукту '{decoded_name}'",
"available_fields": list(nutrients.keys())
}), 404
if __name__ == "__main__":
app.run(debug=True)