Skip to content

Commit a323c41

Browse files
author
Vianpyro
committed
Add endpoint to create a new recipe and improve database cursor management
1 parent dc814c0 commit a323c41

File tree

2 files changed

+64
-1
lines changed

2 files changed

+64
-1
lines changed

routes/recipe.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,64 @@ def get_recipe_tags(recipe_id):
6868
cursor.callproc("get_recipe_tags", (recipe_id,))
6969
tags = cursor.fetchall()
7070
return jsonify(tags)
71+
72+
73+
@recipe_blueprint.route("", methods=["POST"])
74+
def add_recipe():
75+
data = request.json
76+
77+
# Extract recipe data
78+
author_id = data.get("author_id")
79+
picture_id = data.get("picture_id", None)
80+
cook_time = data.get("cook_time")
81+
difficulty_level = data.get("difficulty_level", None)
82+
recipe_source = data.get("recipe_source", None)
83+
recipe_status = data.get("recipe_status", "draft")
84+
85+
# Extract translation data
86+
language_iso_code = data.get("language_iso_code")
87+
title = data.get("title")
88+
details = data.get("details")
89+
preparation = data.get("preparation")
90+
nutritional_information = data.get("nutritional_information", None)
91+
video_url = data.get("video_url", None)
92+
93+
if not all([author_id, cook_time, language_iso_code, title, details, preparation]):
94+
return jsonify({"error": "Missing required fields"}), 400
95+
96+
try:
97+
with database_cursor() as cursor:
98+
cursor.callproc(
99+
"insert_recipe",
100+
(
101+
author_id,
102+
picture_id,
103+
cook_time,
104+
difficulty_level,
105+
recipe_source,
106+
recipe_status,
107+
),
108+
)
109+
cursor.execute("SELECT LAST_INSERT_ID()")
110+
recipe_id = list(cursor.fetchone().values())[0]
111+
112+
cursor.callproc(
113+
"insert_recipe_translation_by_iso_code",
114+
(
115+
recipe_id,
116+
language_iso_code,
117+
title,
118+
details,
119+
preparation,
120+
nutritional_information,
121+
video_url,
122+
),
123+
)
124+
125+
return jsonify({"message": "Recipe added successfully"}), 201
126+
127+
except Exception as e:
128+
import traceback
129+
130+
traceback.print_exc()
131+
return jsonify({"error": f"An error occurred: {str(e)}"}), 500

utility.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,15 @@
1515
@contextmanager
1616
def database_cursor():
1717
db = get_db_connection()
18+
cursor = db.cursor()
1819
try:
19-
yield db.cursor()
20+
yield cursor
2021
db.commit()
2122
except Exception as e:
2223
db.rollback()
2324
raise e
2425
finally:
26+
cursor.close()
2527
db.close()
2628

2729

0 commit comments

Comments
 (0)