from apiflask import Schema
from apiflask.fields import Integer, String
from apiflask.validators import Length, OneOf
classPetInSchema(Schema):
name = String(required=True, validate=Length(0, 10))
category = String(required=True, validate=OneOf(['dog', 'cat']))
classPetOutSchema(Schema):id = Integer()
name = String()
category = String()
from apiflask import APIFlask, input, output
from flask_sqlalchemy import SQLAlchemy
from app.models import Pet
from app.schemas import PetInSchema, PetOutSchema
app = APIFlask(__name__)
db = SQLAlchemy(app)
@app.get('/pets/<int:pet_id>')@output(PetOutSchema) # <-- HIGHLIGHT THIS LINEdefget_pet(pet_id):return Pet.query.get_or_404(pet_id)
@app.patch('/pets/<int:pet_id>')@input(PetInSchema(partial=True)) # <-- HIGHLIGHT THIS LINE@output(PetOutSchema) # <-- AND THIS LINEdefupdate_pet(pet_id, data):
pet = Pet.query.get_or_404(pet_id)
for attr, value in data.items():
setattr(pet, attr, value)
db.session.commit()
return pet