예제 #1
0
 def post(self, *args):
     json_data = json.dumps(request.json)
     try:
         res = AuthorSchema().loads(json_data)
         res = json.loads(AuthorSchema().dumps(res))
         Author.objects.create(**res).save().to_json()
     except ValidationError as error:
         res = error.messages
     return res
예제 #2
0
    def put(self, author_id=None):
        if not author_id:
            return "Відсутній id в url"
        try:
            json_data = json.dumps(request.json)
            try:
                author_data = AuthorSchema().loads(json_data)
                author_data = json.loads(AuthorSchema().dumps(author_data))

                tag = Author(id=author_id)
                tag.update(id=author_id, **author_data)
            except ValidationError as error:
                author_data = error.messages
            return author_data
        except DoesNotExist as error:
            data = "За введеним ID наразі немає записів: " + str(error)
            return data
        except Val_error as error:
            data = "Введений ID у невірному форматі: " + str(error)
            return data
예제 #3
0
    def get(self, author_id=None):
        if author_id:
            try:
                author = Author.objects.get(id=author_id)
                author_posts = Post.objects.filter(author=author_id)

                author = AuthorSchema().dump(author)
                author_posts = PostSchema(exclude=['author']). \
                    dump(author_posts, many=True)

                data = {'author': author, 'posts': author_posts}
                return data
            except DoesNotExist as error:
                data = "За введеним ID наразі немає записів (або отриманий запис має посилання на " \
                       "інший неіснуючий): " + str(error)
                return jsonify(data)
            except Val_error as error:
                data = "Введений ID у невірному форматі:" + str(error)
                return jsonify(data)
        else:
            authors = Author.objects
            return AuthorSchema().dump(authors, many=True)
예제 #4
0
def add_authors(data, many_flag=True):
    try:
        AuthorSchema(many=many_flag).load(data)
    except ValidationError as err:
        return err.messages, 400
    try:
        res = con.execute(meta.tables["authors"].insert(), data)
    except IntegrityError as err:
        return {"message": err.orig.args}, 400

    res.close()

    return {}, 201
예제 #5
0
def get_authors():
    output_data = []
    res = con.execute(meta.tables["authors"].select().order_by(
        meta.tables["authors"].c.article_amount.desc()))

    for i in res:
        output_data.append(dict(i))

    if len(output_data) == 0:
        return {}, 404

    response = AuthorSchema().load(output_data, many=True)
    res.close()

    return response, 200
예제 #6
0
def get_author(author_id):
    output_data = []
    res = con.execute(meta.tables["authors"].select().where(
        meta.tables["authors"].c.id == author_id))

    for i in res:
        output_data.append(dict(i))

    if len(output_data) == 0:
        return {}, 404

    response = AuthorSchema().load(output_data, many=True)
    res.close()

    return response, 200
예제 #7
0
    def delete(self, author_id=None):
        if not author_id:
            return "Відсутній id в url"
        try:
            author_to_delete = Author.objects.get(id=author_id)
            author_to_delete = AuthorSchema().dump(author_to_delete)

            tag = Author(id=author_id)
            tag.delete()
            return author_to_delete
        except DoesNotExist as error:
            data = "За введеним ID наразі немає записів: " + str(error)
            return data
        except Val_error as error:
            data = "Введений ID у невірному форматі: " + str(error)
            return data
예제 #8
0
class AuthorsView(HTTPMethodView):
    schema = AuthorSchema()

    async def get(self, request):  # noqa
        authors = await Author.gino.all()
        resp = self.schema.dump(authors, many=True)
        return make_response(result=resp)

    async def post(self, request):  # noqa
        author_data = request.json or {}

        try:
            validated_data = self.schema.load(author_data)
            author = await Author.create(**validated_data)
        except ValidationError as err:
            return make_response(errors=err.messages, status=400)

        resp = self.schema.dump(author)
        return make_response(result=resp, status=201)
예제 #9
0
class AuthorView(HTTPMethodView):
    schema = AuthorSchema()

    async def get(self, request, author_id):  # noqa
        author = await Author.get_or_404(author_id)
        resp = self.schema.dump(author)
        return make_response(result=resp)

    async def put(self, request, author_id):
        author = await Author.get_or_404(author_id)

        author_data = request.json or {}

        try:
            validated_data = self.schema.load(author_data)
            await author.update(**validated_data).apply()
        except ValidationError as err:
            return make_response(errors=err.messages, status=400)

        resp = self.schema.dump(author)
        return make_response(result=resp, status=200)

    async def delete(self, request, author_id):  # noqa
        author = await Author.get_or_404(author_id)

        try:
            await author.delete()
        except ForeignKeyViolationError:
            # this checks look so weird
            msg = {
                "author_id":
                f"There are several books, referencing author #{author_id}"
            }
            return make_response(errors=msg, status=400)

        make_response(result=f"Author #{author_id} is deleted", status=200)
예제 #10
0
def getauthors():
    authors = session.query(Author).all()
    authorschema = AuthorSchema(many=True)
    data = authorschema.dumps(authors).data
    return data