您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 当前登录用户是否关注当前新闻作者
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
user_id = request.json.get("user_id")
action = request.json.get("action")
if not all([user_id, action]):
return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
if action not in ("follow", "unfollow"):
return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
# 查询到关注的用户信息
try:
target_user = User.query.get(user_id)
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")
if not target_user:
return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")
# 根据不同操作做不同逻辑
if action == "follow":
if target_user.followers.filter(User.id == g.user.id).count() > 0:
return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
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)
paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
# 获取当前页数据
follows = paginate.items
# 获取当前页
current_page = paginate.page
# 获取总页数
total_page = paginate.pages
# 初始化模型,保存数据
comment = Comment()
comment.user_id = user.id
comment.news_id = news_id
comment.content = comment_str
if parent_id:
comment.parent_id = parent_id
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数据已经在模型之中定义,子评论的返回方式,所以会出现评论嵌套。
parent_id = db.Column(db.Integer, db.ForeignKey("info_comment.id")) # 父评论id
parent = db.relationship("Comment", remote_side=[id]) # 自关联
like_count = db.Column(db.Integer, default=0) # 点赞条数
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
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)
# 增加点赞条数
comment.like_count += 1
else:
# 删除点赞数据
comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
if comment_like:
db.session.delete(comment_like)
# 减小点赞条数
comment.like_count -= 1
# 获取当前新闻的评论
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值给前端,用以判断是否显示已经点赞
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)
# 展示是否已经收藏
# 判断是否收藏该新闻,默认值为 false
is_collected = False
# 判断用户是否收藏过该新闻
if g.user:
if news in g.user.collection_news:
is_collected = True
# 登出
session.pop('user_id', None)
session.pop('nick_name', None)
session.pop('mobile', None)
# 登陆
# 从数据库查询出指定的用户,判断已经注册
try:
user = User.query.filter_by(mobile=mobile).first()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg="查询数据错误
if not user:
return jsonify(errno=RET.USERERR, errmsg="用户不存在")
# 校验密码
if not user.check_passowrd(password):
return jsonify(errno=RET.PWDERR, errmsg="密码错误")
# 保存用户登录状态
session["user_id"] = user.id
session["nick_name"] = user.nick_name
session["mobile"] = user.mobile
# 记录用户最后一次登录时间
user.last_login = datetime.now()
# 判断已经登录
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
@admin_blu.route('/user_count')
def user_count():
# 查询总人数
total_count = 0
try:
total_count = User.query.filter(User.is_admin == False).count()
except Exception as e:
current_app.logger.error(e)
# 查询月新增数
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)
# 查询日新增数
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')
# 定义空数组,保存数据
active_date = []
active_count = []
# 依次添加数据,再反转
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"展示新闻内容。
request.method =="POST"提交审核结果。
正常接收两个参数,修改新闻的状态。
若action !=“accept"的话,多接收一个参数。
reason
修改新闻并提交。
# 增加字段,标识新闻的状态
# status = db.Column(db.Integer, default=0) # 当前新闻状态 如果为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)
# 执行审核操作
# 1.获取参数
news_id = request.json.get("news_id")
action = request.json.get("action")
# 2.判断参数
if not all([news_id, action]):
return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
if action not in ("accept", "reject"):
return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
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="未查询到数据")
# 4.根据不同的状态设置不同的值
if action == "accept":
news.status = 0
else:
# 拒绝通过,需要获取原因
reason = request.json.get("reason")
if not reason:
return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
news.reason = reason
news.status = -1
# 保存数据库
try:
db.session.commit()
except Exception as e:
current_app.logger.error(e)
db.session.rollback()
return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
return jsonify(errno=RET.OK, errmsg="操作成功")
keywords = request.args.get("keywords", "") # 设置默认值为空和filters动态变化,目的是为了让直接展示和查询展示走同一接口。
filters = [News.status != 0]
# 如果有关键词
if keywords:
# 添加关键词的检索选项
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)
#分类数据的增删改查
@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="参数错误")
# 判断是否有分类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="查询数据失败")
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="保存数据失败")
return jsonify(errno=RET.OK, errmsg="保存数据成功")
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。