def delete_articles(data): for i in data: if i["id"]: articles_to_delete = i["id"] for article_id in articles_to_delete: try: authors_names = con.execute( select([meta.tables["articles"].c.author ]).where(meta.tables["articles"].c.id == article_id)) for name in authors_names: name = dict(name) delete_articles = con.execute( meta.tables["articles"].delete().where( meta.tables["articles"].c.id == article_id)) delete_articles.close() update_article_counter = con.execute( update(meta.tables["authors"]).where( meta.tables["authors"].c.name == name["author"]). values(article_amount=meta.tables["authors"].c. article_amount - 1)) update_article_counter.close() except IntegrityError as err: return err.args, 400 return {}, 204
def delete_author(author_id): try: delete_author = con.execute(meta.tables["authors"].delete().where( meta.tables["authors"].c.id == author_id)) delete_author.close() except IntegrityError: return "You cannot delete author while his articles are in database.", 400 return {}, 204
def add_articles(data): try: articles = ArticleSchema(many=True, partial=True).load(data) except ValidationError as err: return err.messages, 400 try: insert_articles = con.execute(insert(meta.tables["articles"]), data) insert_articles.close() for article in articles: update_article_counter = con.execute( update(meta.tables["authors"]).where( meta.tables["authors"].c.name == article.author). values(article_amount=meta.tables["authors"].c.article_amount + 1)) update_article_counter.close() except IntegrityError as err: return {"error": err.orig.args}, 400 return {}, 201
def update_article(data, article_id): try: articles = ArticleSchema(partial=True).load(data) except ValidationError as err: return err.messages, 400 res = con.execute(meta.tables["articles"].update().where( meta.tables["articles"].c.id == article_id).values( title=articles.title)) res.close() return {}, 200
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
def get_articles(): output_data = [] res = con.execute(meta.tables["articles"].select().order_by( meta.tables["articles"].c.id.desc())) for i in res: output_data.append(dict(i)) if len(output_data) == 0: return {}, 404 response = ArticleSchema().load(output_data, many=True) res.close() return response, 200
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