溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

網(wǎng)頁返回數(shù)據(jù)的邏輯梳理

發(fā)布時間:2020-07-29 02:55:30 來源:網(wǎng)絡(luò) 閱讀:601 作者:ck_god 欄目:編程語言

第一部分:展示是否已經(jīng)關(guān)注

    # 當前登錄用戶是否關(guān)注當前新聞作者
    is_followed = False
    # 判斷用戶是否收藏過該新聞
    is_collected = False
    if g.user:
        if news in g.user.collection_news:
            is_collected = True
        if news.user.followers.filter(User.id == g.user.id).count() > 0:
            is_followed = True

關(guān)注和取消關(guān)注


    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="參數(shù)錯誤")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="參數(shù)錯誤")

    # 查詢到關(guān)注的用戶信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查詢數(shù)據(jù)庫失敗")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查詢到用戶數(shù)據(jù)")

    # 根據(jù)不同操作做不同邏輯
    if action == "follow":
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="當前已關(guān)注")
        target_user.followers.append(g.user)
    else:
        if target_user.followers.filter(User.id == g.user.id).count() > 0:
            target_user.followers.remove(g.user)

展示我所關(guān)注的作者并分頁

        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 獲取當前頁數(shù)據(jù)
        follows = paginate.items
        # 獲取當前頁
        current_page = paginate.page
        # 獲取總頁數(shù)
        total_page = paginate.pages

第二部分:評論和子評論同一接口,新增評論

    # 初始化模型,保存數(shù)據(jù)
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

展示評論數(shù)據(jù)

    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_list = []
    for item in comments:
        comment_dict = item.to_dict()
        comment_list.append(comment_dict)
    # models里面,前面的略,返回的json數(shù)據(jù)已經(jīng)在模型之中定義,子評論的返回方式,所以會出現(xiàn)評論嵌套。
    parent_id = db.Column(db.Integer, db.ForeignKey("info_comment.id"))  # 父評論id
    parent = db.relationship("Comment", remote_side=[id])  # 自關(guān)聯(lián)
    like_count = db.Column(db.Integer, default=0)  # 點贊條數(shù)

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "content": self.content,
            "parent": self.parent.to_dict() if self.parent else None,
            "user": User.query.get(self.user_id).to_dict(),
            "news_id": self.news_id,
            "like_count": self.like_count
        }
        return resp_dict

第三部分,點贊和點贊計數(shù)

    if action == "add":
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = g.user.id
            db.session.add(comment_like)
            # 增加點贊條數(shù)
            comment.like_count += 1
    else:
        # 刪除點贊數(shù)據(jù)
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            # 減小點贊條數(shù)
            comment.like_count -= 1

展示該條新聞下所有的評論是否已經(jīng)點贊了

    # 獲取當前新聞的評論
    comments = None
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)

    comment_like_ids = []
    if g.user:
        # 如果當前用戶已登錄
        try:
            comment_ids = [comment.id for comment in comments]
            if len(comment_ids) > 0:
                # 取到當前用戶在當前新聞的所有評論點贊的記錄
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),
                                                         CommentLike.user_id == g.user.id).all()
                # 取出記錄中所有的評論id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comment_list = []
    for item in comments if comments else []:
        comment_dict = item.to_dict()
                # 新增key,value值給前端,用以判斷是否顯示已經(jīng)點贊
        comment_dict["is_like"] = False
        # 判斷用戶是否點贊該評論
        if g.user and item.id in comment_like_ids:
                comment_dict["is_like"] = True
        comment_list.append(comment_dict)

第四部分:收藏

# 添加收藏
    if action == "collect":
        user.collection_news.append(news)
    else:
        user.collection_news.remove(news)
# 展示是否已經(jīng)收藏
   # 判斷是否收藏該新聞,默認值為 false
    is_collected = False
    # 判斷用戶是否收藏過該新聞
    if g.user:
        if news in g.user.collection_news:
            is_collected = True

第五部分:登陸,登出,判斷是否已經(jīng)登陸

# 登出
    session.pop('user_id', None)
    session.pop('nick_name', None)
    session.pop('mobile', None)
# 登陸
    #  從數(shù)據(jù)庫查詢出指定的用戶,判斷已經(jīng)注冊
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查詢數(shù)據(jù)錯誤
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用戶不存在")

    # 校驗密碼
    if not user.check_passowrd(password):
        return jsonify(errno=RET.PWDERR, errmsg="密碼錯誤")

    # 保存用戶登錄狀態(tài)
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    # 記錄用戶最后一次登錄時間
    user.last_login = datetime.now()                
# 判斷已經(jīng)登錄
def user_login_data(func):
    @functools.wraps
    def wrappers(*args, **kwargs):
        user_id = session.get("user_id")
        user = None
        if user_id:
            from info.models import User
            user = User.query.get(user_id)
        g.user = user
        return func(*args, **kwargs)
    return wrappers

第六部分:按照日期,統(tǒng)計計數(shù)

@admin_blu.route('/user_count')
def user_count():
    # 查詢總?cè)藬?shù)
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查詢月新增數(shù)
    mon_count = 0
    try:
        now = time.localtime()
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查詢?nèi)招略鰯?shù)
    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 查詢圖表信息
    # 獲取到當天00:00:00時間

    now_date = datetime.strptime(datetime.now().strftime('%Y-%m-%d'), '%Y-%m-%d')
    # 定義空數(shù)組,保存數(shù)據(jù)
    active_date = []
    active_count = []

    # 依次添加數(shù)據(jù),再反轉(zhuǎn)
    for i in range(0, 31):
        begin_date = now_date - timedelta(days=i)
        end_date = now_date - timedelta(days=(i - 1))
        active_date.append(begin_date.strftime('%Y-%m-%d'))
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= day_begin,
                                      User.last_login < day_end).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_date.reverse()
    active_count.reverse()

    data = {"total_count": total_count, "mon_count": mon_count, "day_count": day_count, "active_date": active_date,
            "active_count": active_count}

    return render_template('admin/user_count.html', data=data)

第七部分:審核

request.method == "GET"展示新聞內(nèi)容。
request.method =="POST"提交審核結(jié)果。

正常接收兩個參數(shù),修改新聞的狀態(tài)。
若action !=“accept"的話,多接收一個參數(shù)。
reason
修改新聞并提交。

  # 增加字段,標識新聞的狀態(tài)
   #  status = db.Column(db.Integer, default=0)  # 當前新聞狀態(tài) 如果為0代表審核通過,1代表審核中,-1代表審核不通過
    # reason = db.Column(db.String(256))  # 未通過原因,status = -1 的時候使用

@admin_blu.route('/news_review_detail', methods=["GET", "POST"])
def news_review_detail():
    """新聞審核"""
    if request.method == "GET":
        ...
        return render_template('admin/news_review_detail.html', data=data)

    # 執(zhí)行審核操作

    # 1.獲取參數(shù)
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 2.判斷參數(shù)
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="參數(shù)錯誤")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="參數(shù)錯誤")

    news = None
    try:
        # 3.查詢新聞
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="未查詢到數(shù)據(jù)")

    # 4.根據(jù)不同的狀態(tài)設(shè)置不同的值
    if action == "accept":
        news.status = 0
    else:
        # 拒絕通過,需要獲取原因
        reason = request.json.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="參數(shù)錯誤")
        news.reason = reason
        news.status = -1

    # 保存數(shù)據(jù)庫
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="數(shù)據(jù)保存失敗")
    return jsonify(errno=RET.OK, errmsg="操作成功")

搜索欄的邏輯

       keywords = request.args.get("keywords", "") # 設(shè)置默認值為空和filters動態(tài)變化,目的是為了讓直接展示和查詢展示走同一接口。

        filters = [News.status != 0]
        # 如果有關(guān)鍵詞
        if keywords:
            # 添加關(guān)鍵詞的檢索選項
            filters.append(News.title.contains(keywords))

                       # 查詢
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

第八部分

#分類數(shù)據(jù)的增刪改查

@admin_blu.route('/add_category', methods=["POST"])
def add_category():
    """修改或者添加分類"""

    category_id = request.json.get("id")
    category_name = request.json.get("name")
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg="參數(shù)錯誤")
    # 判斷是否有分類id
    if category_id:
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="查詢數(shù)據(jù)失敗")

        if not category:
            return jsonify(errno=RET.NODATA, errmsg="未查詢到分類信息")

        category.name = category_name
    else:
        # 如果沒有分類id,則是添加分類
        category = Category()
        category.name = category_name
        db.session.add(category)

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存數(shù)據(jù)失敗")
    return jsonify(errno=RET.OK, errmsg="保存數(shù)據(jù)成功")
向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI