from flask import Blueprint, render_template, redirect, url_for, flash from flask_login import login_required, current_user from models import db, User, Follow, Post users_bp = Blueprint('users', __name__) @users_bp.route('/user/') def profile(username): """用户个人主页""" user = User.query.filter_by(username=username).first_or_404() # 只显示已审核的帖子(除非是自己或管理员) if current_user.is_authenticated and (current_user.id == user.id or current_user.is_admin): posts = user.posts.order_by(Post.created_at.desc()).all() else: posts = user.posts.filter_by(is_approved=True).order_by(Post.created_at.desc()).all() follower_count = user.get_follower_count() following_count = user.get_following_count() is_following = False if current_user.is_authenticated: is_following = current_user.is_following(user) return render_template('profile.html', user=user, posts=posts, follower_count=follower_count, following_count=following_count, is_following=is_following) @users_bp.route('/user//follow', methods=['POST']) @login_required def follow(username): """关注用户""" if not current_user.is_approved: flash('您的账号尚未通过审核,无法关注', 'error') return redirect(url_for('users.profile', username=username)) user = User.query.filter_by(username=username).first_or_404() if user.id == current_user.id: flash('不能关注自己', 'error') return redirect(url_for('users.profile', username=username)) if current_user.is_following(user): flash('您已经关注了该用户', 'info') return redirect(url_for('users.profile', username=username)) current_user.follow(user) db.session.commit() flash(f'成功关注 {user.username}', 'success') return redirect(url_for('users.profile', username=username)) @users_bp.route('/user//unfollow', methods=['POST']) @login_required def unfollow(username): """取消关注""" user = User.query.filter_by(username=username).first_or_404() if user.id == current_user.id: flash('不能取消关注自己', 'error') return redirect(url_for('users.profile', username=username)) if not current_user.is_following(user): flash('您还没有关注该用户', 'info') return redirect(url_for('users.profile', username=username)) current_user.unfollow(user) db.session.commit() flash(f'已取消关注 {user.username}', 'success') return redirect(url_for('users.profile', username=username)) @users_bp.route('/user//followers') def followers(username): """粉丝列表""" user = User.query.filter_by(username=username).first_or_404() followers = [follow.follower for follow in user.followers.all()] return render_template('followers.html', user=user, followers=followers) @users_bp.route('/user//following') def following(username): """关注列表""" user = User.query.filter_by(username=username).first_or_404() following = [follow.following for follow in user.following.all()] return render_template('following.html', user=user, following=following)