def show(category_id): schema = CategorySchema() category = Category.get(id=category_id) if not category: abort(404) return schema.dumps(category)
def create(): schema = CategorySchema() try: data = schema.load(request.get_json()) category = Category(**data) db.commit() except ValidationError as err: return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 return schema.dumps(category), 201
def update(category_id): schema = CategorySchema() category = Category.get(id=category_id) if not category: abort(404) try: data = schema.load(request.get_json()) category.set(**data) db.commit() except ValidationError as err: return jsonify({ 'message': 'Validation failed', 'errors': err.messages }), 422 return schema.dumps(category)
def index(): schema = CategorySchema(many=True) categories = Category.select() return schema.dumps(categories)
def get_categories(category_id): schema = CategorySchema() categories = Category.get(id=category_id) return schema.dumps(categories)
from flask import request from flask_restful import Resource from models.Model import db from models.Category import CategorySchema, Category categories_schema = CategorySchema(many=True) category_schema = CategorySchema() class CategoryResource(Resource): def get(self): categories = Category.query.all() categories = categories_schema.dump(categories).data return {'status': 'success', 'data': categories}, 200 def post(self): json_data = request.get_json(force=True) if not json_data: return {'message': 'No input data provided'}, 400 # Validate and deserialize input data, errors = category_schema.load(json_data) if errors: return errors, 422 category = Category.query.filter_by(name=data['name']).first() if category: return {'message': 'Category already exists'}, 400 category = Category(name=json_data['name']) db.session.add(category) db.session.commit()