class CategorySchema(ma.SQLAlchemyAutoSchema): image = AbsoluteURLFor('uploaded_file', filename='<image>') class Meta: model = Category include_fk = True load_instance = True
class HitsSchema(ModelSchema): """Schema to serialize list of hit objects""" title_url = AbsoluteURLFor("get_hit_detail", hit_id="<id>") class Meta: model = Hits fields = ("id", "title", "title_url")
class SingleHitSchema(ModelSchema): """Schema to serialize single hit object""" title_url = AbsoluteURLFor("get_hit_detail", hit_id="<id>") artist = Nested(ArtistSchema) class Meta: model = Hits exclude = ["updated_at"]
class UserSchema(ma.SQLAlchemyAutoSchema): image = AbsoluteURLFor('uploaded_file', filename='<image>') password = ma.String( load_only=True, required=True, ) email = fields.Email(required=True, unique=True, validate=[validate.Length(min=1)]) class Meta: model = User load_instance = True exclude = ('is_superuser', 'is_active')
class StorySchema(ma.SQLAlchemyAutoSchema): image = AbsoluteURLFor('uploaded_file', filename='<image>') class Meta: model = Story include_fk = True load_instance = True @validates('category_id') def validate_category_id(self, category_id): """'value' is the datetime parsed from time_created by marshmallow""" category = Category.query.filter_by(id=category_id).first() if not category: raise ValidationError( f'Category with "{category_id}" pk not found')
class UserSchema(ma.SQLAlchemyAutoSchema): image = AbsoluteURLFor( 'uploaded_file', filename='<image>' ) password = ma.String(load_only=True, required=True) email = fields.Email(required=True, validate=[validate.Length(min=1)]) class Meta: model = User load_instance = True exclude = ('is_superuser', 'is_active') @validates('email') def validate_user_email(self, email): user = User.query.filter_by(email=email).first() if user: raise ValidationError(f'This "{email}" email is available to the user')
class RecipeSchema(ma.SQLAlchemyAutoSchema): image = AbsoluteURLFor('api.uploaded_file', filename='<image>') owner_full_name = fields.Method('get_owner_name', dump_only=True) class Meta: model = Recipe include_fk = True load_instance = True def get_owner_name(self, recipe): return recipe.users.get_full_name @validates('category_id') def validate_category_id(self, category_id): """'value' is the datetime parsed from time_created by marshmallow""" category = Category.query.filter_by(id=category_id).first() print('category', category) if not category: raise ValidationError( f'Category with "{category_id}" pk not found')
def add_href_field(self): model_name = self.Meta.model.__tablename__ endpoint = f"{model_name}_api/show" url_field = AbsoluteURLFor(endpoint, id="<id>") self._declared_fields["href"] = url_field