Flask Vue.js全栈开发|第10章:用户通知

  • 原创
  • Madman
  • /
  • /
  • 0
  • 13808 次阅读

flask vuejs 全栈开发-min.png

Synopsis: 实现动态通知已登录的用户,你的文章有新的评论了、你有新的粉丝了、你的评论被人点赞了、你关注的大神又发布新文章了,新的内容会在头像左上角打上红色小点标记,以提醒用户; 通知功能是非常重要和实用的,我设置的时间轮询间隔为 10 秒,你也可以改大一点

代码已上传到 https://github.com/wangy8961/flask-vuejs-madblog/tree/v0.10 ,欢迎star

1. 用户收到的评论

1.1 增加 API

用户发布文章后,陆续有其它用户在下面评论了,此时,文章作者需要知道他的哪篇文章有新评论了

修改 back-end/app/models.py

class User(PaginatedAPIMixin, db.Model):
    ...
    # 用户最后一次查看 收到的评论 页面的时间,用来判断哪些收到的评论是新的
    last_recived_comments_read_time = db.Column(db.DateTime)

数据库迁移:

(venv) D:\python-code\flask-vuejs-madblog\back-end>flask db migrate -m "which recived comments are new"
(venv) D:\python-code\flask-vuejs-madblog\back-end>flask db upgrade

修改 back-end/app/api/users.py

@bp.route('/users/<int:id>/recived-comments/', methods=['GET'])
@token_auth.login_required
def get_user_recived_comments(id):
    '''返回该用户收到的所有评论'''
    user = User.query.get_or_404(id)
    if g.current_user != user:
        return error_response(403)
    page = request.args.get('page', 1, type=int)
    per_page = min(
        request.args.get(
            'per_page', current_app.config['COMMENTS_PER_PAGE'], type=int), 100)
    # 用户发布的所有文章ID集合
    user_posts_ids = [post.id for post in g.current_user.posts.all()]
    # 评论的 post_id 在 user_posts_ids 集合中,且评论的 author 不是当前用户(即文章的作者)
    data = Comment.to_collection_dict(
        Comment.query.filter(Comment.post_id.in_(user_posts_ids), Comment.author != g.current_user)
        .order_by(Comment.mark_read, Comment.timestamp.desc()),
        page, per_page, 'api.get_user_recived_comments', id=id)
    # 标记哪些评论是新的
    last_read_time = user.last_recived_comments_read_time or datetime(1900, 1, 1)
    for item in data['items']:
        if item['timestamp'] > last_read_time:
            item['is_new'] = True
    # 更新 last_recived_comments_read_time 属性值
    user.last_recived_comments_read_time = datetime.utcnow()
    db.session.commit()
    return jsonify(data)

1.2 前端路由

修改 front-end/router/index.js

// 用户通知
import Notifications from '@/components/Notifications/Notifications'
import RecivedComments from '@/components/Notifications/RecivedComments'

const router = new Router({
  mode: 'history',
  routes: [
    ...
    {
      // 用户通知
      path: '/notifications',
      component: Notifications,
      children: [
        { path: '', component: RecivedComments },
        { path: 'comments', name: 'RecivedComments', component: RecivedComments }
      ],
      meta: {
        requiresAuth: true
      }
    },
    ...
  ]
})

创建 front-end/components/Notifications/Notification.vuefront-end/components/Notifications/RecivedComments.vue 组件,使用 嵌套路由,代码见 Github 仓库

如果是新的评论,则在评论用户的头像左上角显示红点

1 用户新收到评论的静态提示

2. 动态通知

现在只有当用户自己访问 http://localhost:8080/notifications/comments 页面才能知道有没有收到新的评论,我们需要实现在 Navbar 导航栏上显示新评论的数目,提醒用户查看

除了新评论通知以外,我们后续还可以实现有新的点赞了通知我、有新粉丝了通知我、我关注的大神们发布新文章了通知我、有新私信了通知我等等,所以这里增加一个 Notification 数据模型,它用来存储每个用户的某一类通知

修改 back-end/app/models.py

class User(PaginatedAPIMixin, db.Model):
    ...
    # 用户的通知
    notifications = db.relationship('Notification', backref='user',
                                    lazy='dynamic', cascade='all, delete-orphan')


class Notification(db.Model):  # 不需要分页
    __tablename__ = 'notifications'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(128), index=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    timestamp = db.Column(db.Float, index=True, default=time)
    payload_json = db.Column(db.Text)

    def __repr__(self):
        return '<Notification {}>'.format(self.id)

    def get_data(self):
        return json.loads(str(self.payload_json))

    def to_dict(self):
        data = {
            'id': self.id,
            'name': self.name,
            'user': {
                'id': self.user.id,
                'username': self.user.username,
                'name': self.user.name,
                'avatar': self.user.avatar(128)
            },
            'timestamp': self.timestamp,
            'payload': self.get_data(),
            '_links': {
                'self': url_for('api.get_notification', id=self.id),
                'user_url': url_for('api.get_user', id=self.user_id)
            }
        }
        return data
                                
                            
  • 126039858
  • zhuyulin
  • ygren
  • wulvtutu
  • 99857443
  • nickzxhfjsm
  • que-ai2023
  • anthony-577518830
  • team12
  • reinxd
  • 11757580
  • qiu-chen-100
  • 61450478
  • 19979360
  • 36176728
  • 93176860
  • 96768625
  • luohuai1q84
  • binrr
  • zscsd
  • seesea
  • mingyun
  • 415670177
  • 49409355
未经允许不得转载: LIFE & SHARE - 王颜公子 » Flask Vue.js全栈开发|第10章:用户通知

分享

作者

作者头像

Madman

如需 Linux / Python 相关问题付费解答,请按如下方式联系我

0 条评论

暂时还没有评论.

专题系列