您好,登錄后才能下訂單哦!
# 當前登錄用戶是否關注當前新聞作者
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。