예제 #1
0
 def test_food_to_dict(self):
     u = push_dummy_user()
     list_ = push_dummy_list(u, 'List')
     a = Food(list_id=list_.id, name='Food')
     db.session.add(a)
     db.session.commit()
     self.assertEqual(a.to_dict(), {
         'id': 1,
         'name': 'Food',
         'categories': []
     })
     cat = FoodCategory(list_id=list_.id, name='Cat')
     db.session.add(cat)
     db.session.commit()
     catass = FoodCategoryAssociation(food_id=a.id, category_id=cat.id)
     db.session.add(catass)
     db.session.commit()
     self.assertEqual(a.to_dict(), {
         'id': 1,
         'name': 'Food',
         'categories': [1]
     })
예제 #2
0
def post_foods(list_id):
    req = request.get_json()
    if not req:
        raise APIError("application/json is required")
    if "name" not in req:
        raise APIError("name is required")
    list_ = List.query.filter_by(id=list_id).first()
    if Food.query.filter_by(name=req["name"], list_id=list_.id).first():
        raise APIError(f'Food {req["name"]} already exists')
    food = Food(list_id=list_.id, name=req["name"])
    db.session.add(food)
    db.session.commit()
    json_obj = [food.to_dict() for food in list_.foods]
    return jsonify(json_obj), 201