|
| 1 | +from .. import api, db |
| 2 | +from ..articles.decorators import article_exists, valid_article_form, article_table_empty |
| 3 | +from ..articles.utils import create_article, update_article |
| 4 | +from ..articles.schemas import article_schema, articles_schema |
| 5 | +from flask import Blueprint, request |
| 6 | +from flask_restful import Resource |
| 7 | +from ..models import Article |
| 8 | + |
| 9 | +# Blueprint for articles |
| 10 | +articles_bp = Blueprint("articles", __name__) |
| 11 | + |
| 12 | + |
| 13 | +# Class to handle information regarding the Article model |
| 14 | +class Articles(Resource): |
| 15 | + |
| 16 | + # Function to create an article |
| 17 | + @valid_article_form |
| 18 | + def post(self): |
| 19 | + form_data = request.get_json() |
| 20 | + article = create_article(form_data) |
| 21 | + |
| 22 | + db.session.add(article) |
| 23 | + db.session.commit() |
| 24 | + |
| 25 | + return {"message": "Successfully created Article"}, 201 |
| 26 | + |
| 27 | + # Function to display all the articles up to a limit of 15 |
| 28 | + @article_table_empty |
| 29 | + def get(self): |
| 30 | + article = Article.query.limit(15) |
| 31 | + return articles_schema.dump(article, default=str) |
| 32 | + |
| 33 | + |
| 34 | +class ArticleCRUD(Resource): |
| 35 | + |
| 36 | + # Function to edit an article |
| 37 | + @valid_article_form |
| 38 | + @article_exists |
| 39 | + def put(self, article_id): |
| 40 | + article = Article.query.get(article_id) |
| 41 | + form_data = request.get_json() |
| 42 | + update_article(article, form_data) |
| 43 | + |
| 44 | + db.session.commit() |
| 45 | + |
| 46 | + return {"message": "Article successfully updated"}, 200 |
| 47 | + |
| 48 | + # Function to delete an article |
| 49 | + @article_exists |
| 50 | + def delete(self, article_id): |
| 51 | + article = Article.query.get(article_id) |
| 52 | + |
| 53 | + db.session.delete(article) |
| 54 | + db.session.commit() |
| 55 | + |
| 56 | + return {"message": "Article successfully deleted"}, 200 |
| 57 | + |
| 58 | + # Function to display an article |
| 59 | + @article_exists |
| 60 | + def get(self, article_id): |
| 61 | + article = Article.query.get(article_id) |
| 62 | + |
| 63 | + return article_schema.dump(article) |
| 64 | + |
| 65 | +# Creates the routes for the classes |
| 66 | +api.add_resource(Articles, "/api/articles") |
| 67 | +api.add_resource(ArticleCRUD, "/api/articles/<int:article_id>") |
0 commit comments