def recipe_update_create(): """ Take in a JSON object in the form of { "recipes": [ { "rec_id": 1, "rec_name": "Chicken and Rice", "instructions": "Idk, ask mom", "category": <a string value of either entree, appetizer, or dessert>, "ingredients": [ <a list of ingredient ids>] }, ... ] } Where for each entry in "recipes" if there is a "rec_id" attribute, it is assumed that we are updating an existing recipe (because we wouldn't have the id otherwise), and the values given will update the record and its ingredients links in the database. Otherwise, if there is no "rec_id" for an object, the system will assume the values given are for a new record in the database and will create a new record. :return: A JSON object of {"recipes":[<list of recipes updated or created in the system>]} """ if not request.json or len(request.json) == 0: return jsonify({"error": "No JSON supplied"}), 400 id_column = Recipe.__keys__[0] ret_val = [] rec = Recipe() j = request.json if not j.get('recipes', None): return jsonify({"error": "Invalid input schema"}), 400 for recipe in j['recipes']: recipe_id = recipe.get(id_column, None) # Enforce enums if recipe.get("category", None) and recipe['category'] not in Recipe.__columns__['category']: return jsonify({ "error": "Categories must be one of the following: {}".format(Recipe.__columns__['category'])} ), 400 if recipe_id: rec.find_by_id(recipe_id) rec.update(**recipe) rec.flush() else: rec.create(**recipe) if recipe.get('ingredients', None): try: rec.ingredients = recipe['ingredients'] except TypeError: return jsonify({ "error": "Ingredient entries must be a list of ids referencing food items in the database" }), 400 ret_val.append(deepcopy(rec.data)) return jsonify({"recipes": ret_val})
def fetch_recipe_and_ingredients(recipe_id): resp = dynamodb.query( TableName='recipes', KeyConditionExpression="PK = :pk AND SK BETWEEN :metadata AND :ingredients", ExpressionAttributeValues={ ":pk": { "S": "RECIPE#{}".format(recipe_id) }, ":metadata": { "S": "#METADATA#{}".format(recipe_id) }, ":ingredients": { "S": "INGREDIENT$" }, }, ScanIndexForward=True ) recipe = Recipe(resp['Items'][0]) recipe.ingredients = [RecipeIngredientMapping(item) for item in resp['Items'][1:]] return recipe