meal_homework/mealapi/resources/mealbaseresource.py

29 lines
712 B
Python
Raw Normal View History

2022-02-13 20:38:02 +01:00
#!/usr/bin/env python3
from flask_restful import Resource
2022-02-13 22:32:40 +01:00
from flask import request, abort
2022-02-13 20:38:02 +01:00
from marshmallow import ValidationError
2022-02-13 20:52:51 +01:00
from model import db, Meal
from schemas import MealSchema
2022-02-13 20:38:02 +01:00
class MealBaseResource(Resource):
mealschema = MealSchema(many=False)
mealschemas = MealSchema(many=True)
def post(self):
body = request.get_json()
try:
2022-02-13 21:54:43 +01:00
loadedobj = self.mealschema.load(body)
db.session.add(loadedobj)
2022-02-13 21:48:03 +01:00
db.session.commit()
2022-02-13 20:38:02 +01:00
return '', 204
2022-02-13 21:25:37 +01:00
except ValidationError as error:
abort(406, error.messages)
2022-02-13 20:38:02 +01:00
def get(self):
meals = Meal.query.all()
return self.mealschemas.dump(list(meals)), 200