Пример #1
0
def show(category_id):
    schema = CategorySchema()
    category = Category.get(id=category_id)

    if not category:
        abort(404)

    return schema.dumps(category)
Пример #2
0
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
Пример #3
0
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)
Пример #4
0
def index():

    schema = CategorySchema(many=True)
    categories = Category.select()
    return schema.dumps(categories)
Пример #5
0
def get_categories(category_id):

    schema = CategorySchema()
    categories = Category.get(id=category_id)
    return schema.dumps(categories)
Пример #6
0
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()