当前位置:网站首页>Variable star --- article module (1)

Variable star --- article module (1)

2022-07-06 20:38:00 mb61037a3723f67

One : Get article details :

1: Analysis of article detail table :

analysis : To return the content information of the article , Article table , Users of articles . These three kinds of information come from three tables . If User Table as the main table , You cannot query the information of the article , So only the article table can be used as the main table .

 All change star --- Article module (1)_flask

2: Enter the data in the article content table :

mysql -uroot -pmysql -D hm_topnews -h 192.168.44.128 < sql file name

 All change star --- Article module (1)_ data _02

3: Write ideas :

1: First get the parameters , Need to get user's id, as well as is_refresh, Determine whether the user is logged in , And get article_id, The article id, Because we need to according to the article id Query the linked table .
2: Logical processing : The article table is used as the main table , Joint user table and article content table , According to the article id, Query the title of the article , Author information of the article , The content of the article .
3: If the user has logged in , Check whether the user pays attention to the author of the article , Query whether the user has collected this article , And the user's attitude towards the author .
4: Build response returns : Convert the data related to the article into a dictionary and return .

app/resource/article/article.py

from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from app import db
from models.article import Article, ArticleContent
from models.user import User
from utils.contants import HOME_ARTICLE_PERPAGE
from datetime import datetime

class ArticleDetailResource(Resource):
    """  Article details interface class view  """
    #  Which article did the front end pass to me id
    def get(self, article_id):
        # 1:  Get users id
        user_id = g.user_id
        is_refresh = g.is_refresh
        # 2:  Get the article object 
        article = db.session.query(Article.id,
                                   Article.title,
                                   Article.user_id,
                                   Article.ctime,
                                   User.name,
                                   User.profile_photo,
                                   ArticleContent.content)\
            .join(User, Article.user_id == User.id)\
            .join(ArticleContent, Article.id == ArticleContent.article_id)\
            .filter(Article.id == article_id).first()

        print(article)
        # 3:  Convert the data related to the article into a dictionary and return .
        article_dict = {
            "art_id": article.id,   #  The article id
            "title": article.title, #  The title of the article 
            "pubdate": article.ctime.isoformat(),#  Convert to article date string 
            "aut_id": article.user_id,#  Author of the article id
            "aut_name": article.name, #  The name of the author of the article , Because of linked table query ,name refer to User The author of the article in id
            "aut_photo": article.profile_photo, #  The portrait of the author of the article 
            "content": article.content,#  The content of the article 
            "is_followed": False,
            "attitude": -1,
            "is_collected": False
        }

        return article_dict

      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

test — Return the default information when you are not logged in :

4: Pay attention to the author's implementation :

1: Code implementation :

class ArticleDetailResource(Resource):
    """  Article details interface class view  """
    #  Which article did the front end pass to me id
    def get(self, article_id):
        # 1:  Get users id
        user_id = g.user_id
        is_refresh = g.is_refresh
        # 2:  Get the article object 
        article = db.session.query(Article.id,
                                   Article.title,
                                   Article.user_id,
                                   Article.ctime,
                                   User.name,
                                   User.profile_photo,
                                   ArticleContent.content)\
            .join(User, Article.user_id == User.id)\
            .join(ArticleContent, Article.id == ArticleContent.article_id)\
            .filter(Article.id == article_id).first()


        article_dict = {
            "art_id": article.id,  #  The article id
            "title": article.title,  #  The title of the article 
            "pubdate": article.ctime.isoformat(),  #  Convert to article date string 
            "aut_id": article.user_id,  #  Author of the article id
            "aut_name": article.name,  #  The name of the author of the article , Because of linked table query ,name refer to User The author of the article in id
            "aut_photo": article.profile_photo,  #  The portrait of the author of the article 
            "content": article.content,  #  The content of the article 
            "is_followed": False,
            "attitude": -1,
            "is_collected": False
        }
        #  article id
        article_id = article.id
        #  The authors id
        author_id = article.user_id
        #  If the user logs in 
        if user_id and is_refresh is False:
            #  Check whether the user pays attention to the author of the article --- Query the user fan relationship table ( Autocorrelation many to many )
            #  You only need to query the data in the relational table , So use slow query to only check id
            #  Query criteria : Users in the relationship table id, Equal to the current user's id, The author in the relation table id Equal to the author of this article id,  And the relationship between the two is the relationship of concern .
            relation = Relation.query.options(load_only(Relation.id))\
                .filter(Relation.user_id == user_id, Relation.author_id == author_id, Relation.relation == Relation.RELATION.FOLLOW)
            #  If we can find the relationship between the two , Modify the relationship of the dictionary 
            article_dict['is_followed'] = True if relation else False

        return article_dict

      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.

2: Add fields to the database :6 User No 1 No. author :
 All change star --- Article module (1)_ database _03
3: test :
 All change star --- Article module (1)_ other _04

5: Collection relationship and attitude relationship :

1: Add the relationship between users and articles collection and the attitude relationship between users and articles in the database .
 All change star --- Article module (1)_ other _05
 All change star --- Article module (1)_ database _06

2: Code implementation :

class ArticleDetailResource(Resource):
    """  Article details interface class view  """
    #  Which article did the front end pass to me id
    def get(self, article_id):
        # 1:  Get users id
        user_id = g.user_id
        is_refresh = g.is_refresh
        # 2:  Get the article object 
        article = db.session.query(Article.id,
                                   Article.title,
                                   Article.user_id,
                                   Article.ctime,
                                   User.name,
                                   User.profile_photo,
                                   ArticleContent.content)\
            .join(User, Article.user_id == User.id)\
            .join(ArticleContent, Article.id == ArticleContent.article_id)\
            .filter(Article.id == article_id).first()


        article_dict = {
            "art_id": article.id,  #  The article id
            "title": article.title,  #  The title of the article 
            "pubdate": article.ctime.isoformat(),  #  Convert to article date string 
            "aut_id": article.user_id,  #  Author of the article id
            "aut_name": article.name,  #  The name of the author of the article , Because of linked table query ,name refer to User The author of the article in id
            "aut_photo": article.profile_photo,  #  The portrait of the author of the article 
            "content": article.content,  #  The content of the article 
            "is_followed": False,
            "attitude": -1,
            "is_collected": False
        }
        #  article id
        article_id = article.id
        #  The authors id
        author_id = article.user_id
        #  If the user logs in 
        if user_id and is_refresh is False:
            #  Check whether the user pays attention to the author of the article --- Query the user fan relationship table ( Autocorrelation many to many )
            #  You only need to query the data in the relational table , So use slow query to only check id
            #  Query criteria : Users in the relationship table id, Equal to the current user's id, The author in the relation table id Equal to the author of this article id,  And the relationship between the two is the relationship of concern .
            relation = Relation.query.options(load_only(Relation.id))\
                .filter(Relation.user_id == user_id, Relation.author_id == author_id, Relation.relation == Relation.RELATION.FOLLOW)
            #  If we can find the relationship between the two , Modify the relationship of the dictionary 
            article_dict['is_followed'] = True if relation else False

            #  Query the collection relationship between users and articles 
            #  The user in the collection relationship id Equal to the current user's id,  Articles browsed by users id Is it equal to the article of the collection table id
            collection = Collection.query.options(load_only(Collection.id))\
                .filter(Collection.user_id == user_id,
                        Collection.article_id == article_id,
                        Collection.is_deleted == False).first()
            article_dict['is_collected'] = True if collection else False

            #  Query the attitude relationship between users and articles :
            attitude_obj = Attitude.query.options(load_only(Attitude.attitude))\
                .filter(Attitude.user_id == user_id, Attitude.article_id == article_id).first()

            print(attitude_obj)
            if attitude_obj:
                article_dict['attitude'] = attitude_obj.attitude
            else:
                article_dict['attitude'] = Attitude.ATTITUDE.DELETE


        return article_dict


      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.

 All change star --- Article module (1)_ data _07

Two : Focus on users :

1: Demand analysis :

1: To obtain parameters : User id, The author's id.
2: Business logic : According to the user id And the author id Query in the following table , Three relationships are known [ Focus on =1, No attention to =0, Pull black =2], If the data is queried in the database, it may be concerned or hacked , Send this follow interface request , It can only be attention , Therefore, modify the relationship to focus on the relationship , And modify the time of concern .
3: If there is no data in the database , Explain that I haven't paid attention to , Therefore, we need to add data to the database .
4: After clicking on the user's attention , The number of users' followers should be increased 1, The number of fans of the author is also increased by one .

2: Code implementation :

Interface code :

import datetime

from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from sqlalchemy.orm import load_only

from app import db
from models.user import Relation, User


class FollowingUserResource(Resource):
    """  Focus on interfaces  """
    def post(self):
        # 1:  To obtain parameters 
        user_id = g.user_id
        parser = RequestParser()
        parser.add_argument("author_id", type=int, location="json", required= True)
        ret = parser.parse_args()
        author_id = ret['author_id']

        # 2: According to the user id And the author id Query the relationship object 
        relation_obj = Relation.query.options(load_only(Relation.id))\
            .filter(Relation.user_id == user_id, Relation.author_id == author_id).first()

        #  If you find , Change the relationship to focus , And update time 
        if relation_obj:
            relation_obj.relation = Relation.RELATION.FOLLOW
            relation_obj.update_time = datetime.datetime.now()
        #  If... Is not found in the relationship table , Create a new... In the relationship table .
        else:
            relation_obj = Relation(user_id=user_id, author_id=author_id, relation=Relation.RELATION.FOLLOW)
            db.session.add(relation_obj)
        #  Increase the number of users' attention 1
        User.query.filter(User.id == user_id).update({"following_count": User.following_count+1})
        #  Increase the number of authors' attention 1
        User.query.filter(User.id == author_id).update({"fans_count": User.fans_count + 1})

        try:
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            return {"message": " Focus on exceptions : {}".format(e)}, 507
        return {"message": " Focus on success ","author_id":author_id}

      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

Routing code :

article_api.add_resource(FollowingUserResource, "/following")

      
  • 1.

test :
 All change star --- Article module (1)_ other _08
 All change star --- Article module (1)_ data _09

3、 ... and : Cancel paying attention to the interface :

1: Interface code :

class UnFlollowingUserResource(Resource):

    #  Login decorator 
    method_decorators = {
        "delete": [login_required]
    }

    #  Need to pass in the author's id
    def delete(self, author_id):
        #  Gets the current user's id
        user_id = g.user_id
        #  According to the user's id And the author's id, Update to cancel the following status , Update the following time 
        Relation.query.filter(Relation.user_id == user_id,
                              Relation.author_id == author_id,
                              Relation.relation == Relation.RELATION.FOLLOW)\
            .update({"relation": Relation.RELATION.DELETE, "update_time": datetime.datetime.now()})

        #  Reduce the number of users' attention by one :
        User.query.filter(User.id == user_id).update({"following_count": User.following_count -1 })
        #  Reduce the number of fans of the author by one :
        User.query.filter(User.id == author_id).update({"fans_count": User.fans_count - 1})

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            return {"messgae": " Failed to cancel the attention and save the data to the database : {}".format(e)}, 507

        return {"messgae": " Cancel focus on success ", "author_id": author_id}


      
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

2: route :

article_api.add_resource(UnFlollowingUserResource, "/unfollowings/<int:author_id>")

      
  • 1.

3: test :
 All change star --- Article module (1)_ data _10
 All change star --- Article module (1)_flask_11

原网站

版权声明
本文为[mb61037a3723f67]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131157406505.html