def recipe_get(recipe_id): """Provide the recipe for recipe_id""" try: recipe = next(db.helpers.select_recipes(models.Recipe.id == recipe_id)) except StopIteration: raise exc.APIException('recipe not found', 404) return schemas.recipe.dump(recipe).data
def recipe_put(recipe_id): """Update a specified recipe""" recipe = helpers.raise_or_return(schemas.recipe.put) if not recipe: raise exc.APIException('no data provided for update') recipe['id'] = recipe_id recipe = db_helpers.update_recipe(recipe) return schemas.recipe.dump(recipe).data
def utensil_put(utensil_id): """Update the utensil for utensil_id""" utensil = helpers.raise_or_return(schemas.utensil.put) if not utensil: raise exc.APIException('no data provided for update') utensil['id'] = utensil_id utensil = db_helpers.update(models.Utensil, utensil) return schemas.utensil.dump(utensil).data
def utensils_post(): """Create an utensil""" utensil = helpers.raise_or_return(schemas.utensil.post) try: utensil = models.Utensil.create(**utensil) except peewee.IntegrityError: raise exc.APIException('utensil already exists', 409) return schemas.utensil.dump(utensil).data, 201
def update(model, value): """Update an elt and return it""" try: return (model .update(**value) .where(model.id == value.pop('id')) .returning() .execute() .next()) except StopIteration: raise exc.APIException('%s not found' % model._meta.name, 404)
def raise_or_return(schema, many=False): """Load the data in a dict, if errors are returned, an error is raised""" data = flask.request.get_json() if is_iterable(data): data, errors = schema.load(data, many) else: errors = 'JSON is incorrect' if errors: raise exc.APIException('request malformed', 400, {'errors': errors}) return data
def recipes_post(): """Create a recipe""" recipe = helpers.raise_or_return(schemas.recipe.post) utensils = recipe.pop('utensils') ingredients = recipe.pop('ingredients') try: recipe = models.Recipe.create(**recipe) except peewee.IntegrityError: raise exc.APIException('recipe already exists', 409) db_helpers.recipe_insert_utensils(recipe.id, utensils) db_helpers.recipe_insert_ingredients(recipe.id, ingredients) recipe.utensils = utensils recipe.ingredients = ingredients return schemas.recipe.dump(recipe).data, 201
def on_json_loading_failed(self, _): raise exc.APIException('request malformed', 400, {'errors': 'JSON is incorrect'})
def get(model, pk): """Get a specific elt or raise 404 if it does not exists""" try: return model.get(model.id == pk) except peewee.DoesNotExist: raise exc.APIException('%s not found' % model._meta.name, 404)