Esempio n. 1
0
def new_smoothie():
    if not request.json or not 'name' in request.json:
        abort(400)

    if Smoothie.query.filter_by(name=request.json["name"]).first() is not None:
        return {
            "error":
            "Smoothie {} already present in application".format(
                request.json["name"])
        }, 400

    smoothie = Smoothie()
    smoothie.import_data(request.json)

    for new_ingredient in request.json["ingredients"]:
        ingredient = Ingredient()
        # Check if ingredient is already in the database
        if Ingredient.query.filter_by(name=new_ingredient).first() is None:
            ingredient.import_data(new_ingredient)
            db.session.add(ingredient)
        else:
            ingredient = Ingredient.query.filter_by(
                name=new_ingredient).first()
        smoothie.recipe.append(ingredient)

    db.session.add(smoothie)
    db.session.commit()

    return {}, 201
Esempio n. 2
0
def edit_smoothie(id):
    smoothie = Smoothie.query.get_or_404(id)
    if not smoothie:
        return {"error": "no resource found"}, 404

    smoothie.import_data(request.json)
    smoothie.recipe = []
    for ingredient in request.json["ingredients"]:
        new_ingredient = Ingredient.query.filter_by(name=ingredient).first()
        if new_ingredient is None:
            new_ingredient = Ingredient()
            new_ingredient.import_data(ingredient)
            db.session.add(new_ingredient)
        else:
            new_ingredient = Ingredient.query.filter_by(
                name=ingredient).first()
        smoothie.recipe.append(new_ingredient)

    db.session.add(smoothie)
    db.session.commit()

    db.session.add(smoothie)
    db.session.commit()
    return {"message": "Resource succesfully updated"}