コード例 #1
0
ファイル: following.py プロジェクト: dylankung/toutiao
    def get(self):
        """
        获取关注的用户列表
        """
        qs_parser = RequestParser()
        qs_parser.add_argument('page', type=inputs.positive, required=False, location='args')
        qs_parser.add_argument('per_page', type=inputs.int_range(constants.DEFAULT_USER_FOLLOWINGS_PER_PAGE_MIN,
                                                                 constants.DEFAULT_USER_FOLLOWINGS_PER_PAGE_MAX,
                                                                 'per_page'),
                               required=False, location='args')
        args = qs_parser.parse_args()
        page = 1 if args.page is None else args.page
        per_page = args.per_page if args.per_page else constants.DEFAULT_USER_FOLLOWINGS_PER_PAGE_MIN

        results = []
        followings = cache_user.UserFollowingCache(g.user_id).get()
        followers = cache_user.UserFollowersCache(g.user_id).get()
        total_count = len(followings)
        req_followings = followings[(page-1)*per_page:page*per_page]
        for following_user_id in req_followings:
            user = cache_user.UserProfileCache(following_user_id).get()
            results.append(dict(
                id=following_user_id,
                name=user['name'],
                photo=user['photo'],
                fans_count=user['fans_count'],
                mutual_follow=following_user_id in followers
            ))

        return {'total_count': total_count, 'page': page, 'per_page': per_page, 'results': results}
コード例 #2
0
    def post(self):
        """
        关注用户
        """
        json_parser = RequestParser()
        json_parser.add_argument('target',
                                 type=parser.user_id,
                                 required=True,
                                 location='json')
        args = json_parser.parse_args()
        target = args.target
        if target == g.user_id:
            return {'message': 'User cannot follow self.'}, 400
        ret = 1
        try:
            follow = Relation(user_id=g.user_id,
                              target_user_id=target,
                              relation=Relation.RELATION.FOLLOW)
            db.session.add(follow)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            ret = Relation.query.filter(Relation.user_id == g.user_id,
                                        Relation.target_user_id == target,
                                        Relation.relation != Relation.RELATION.FOLLOW)\
                .update({'relation': Relation.RELATION.FOLLOW})
            db.session.commit()

        if ret > 0:
            timestamp = time.time()
            cache_user.UserFollowingCache(g.user_id).update(target, timestamp)
            cache_user.UserFollowersCache(target).update(g.user_id, timestamp)
            cache_statistic.UserFollowingsCountStorage.incr(g.user_id)
            cache_statistic.UserFollowersCountStorage.incr(target)
            cache_user.UserRelationshipCache(g.user_id).clear()

        # 发送关注通知
        _user = cache_user.UserProfileCache(g.user_id).get()
        _data = {
            'user_id': g.user_id,
            'user_name': _user['name'],
            'user_photo': _user['photo'],
            'timestamp': int(time.time())
        }
        # 通过socketio提供的kombu管理对象 向rabbitmq中写入数据,记录需要由socketio服务器向客户端推送消息的任务
        current_app.sio_mgr.emit('following notify',
                                 data=_data,
                                 room=str(target))

        return {'target': target}, 201
コード例 #3
0
ファイル: following.py プロジェクト: dylankung/toutiao
    def delete(self, target):
        """
        取消关注用户
        """
        ret = Relation.query.filter(Relation.user_id == g.user_id,
                                    Relation.target_user_id == target,
                                    Relation.relation == Relation.RELATION.FOLLOW)\
            .update({'relation': Relation.RELATION.DELETE})
        db.session.commit()

        if ret > 0:
            timestamp = time.time()
            cache_user.UserFollowingCache(g.user_id).update(target, timestamp, -1)
            cache_user.UserFollowersCache(target).update(g.user_id, timestamp, -1)
            cache_statistic.UserFollowingsCountStorage.incr(g.user_id, -1)
            cache_statistic.UserFollowersCountStorage.incr(target, -1)
        return {'message': 'OK'}, 204
コード例 #4
0
ファイル: blacklist.py プロジェクト: dylankung/toutiao
    def post(self):
        """
        拉黑用户
        """
        json_parser = RequestParser()
        json_parser.add_argument('target',
                                 type=parser.user_id,
                                 required=True,
                                 location='json')
        args = json_parser.parse_args()
        target = args.target
        if target == g.user_id:
            return {'message': 'User cannot blacklist self.'}, 400
        try:
            blacklist = Relation(user_id=g.user_id,
                                 target_user_id=target,
                                 relation=Relation.RELATION.BLACKLIST)
            db.session.add(blacklist)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            fol_ret = 0
            # Change relation from DELETE to BLACKLIST
            del_ret = Relation.query.filter(Relation.user_id == g.user_id,
                                        Relation.target_user_id == target,
                                        Relation.relation == Relation.RELATION.DELETE) \
                .update({'relation': Relation.RELATION.BLACKLIST})
            if del_ret == 0:
                # Change relation from FOLLOW to BLACKLIST
                fol_ret = Relation.query.filter(Relation.user_id == g.user_id,
                                            Relation.target_user_id == target,
                                            Relation.relation == Relation.RELATION.FOLLOW) \
                    .update({'relation': Relation.RELATION.BLACKLIST})

            db.session.commit()

            if fol_ret > 0:
                timestamp = time.time()
                cache_user.UserFollowingCache(g.user_id).update(
                    target, timestamp, -1)
                cache_user.UserFollowersCache(target).update(
                    g.user_id, timestamp, -1)
                cache_statistic.UserFollowingsCountStorage.incr(g.user_id, -1)
                cache_statistic.UserFollowersCountStorage.incr(target, -1)

        return {'target': target}, 201
コード例 #5
0
    def get(self, target):
        """
        获取target用户的数据
        :param target: 目标用户id
        """
        cache = cache_user.UserProfileCache(target)
        exists = cache.exists()
        if not exists:
            return {'message': 'Invalid target user.'}, 400

        user_data = cache.get()

        user_data['is_following'] = False
        if g.user_id:
            # Check if user has followed target user.
            # ret = Relation.query.options(load_only(Relation.id))\
            #     .filter_by(user_id=g.user_id, target_user_id=target, relation=Relation.RELATION.FOLLOW).first()
            # user_data['is_following'] = cache_user.determine_user_follows_target(g.user_id, target)
            user_data['is_following'] = cache_user.UserFollowingCache(
                g.user_id).determine_follows_target(target)

        user_data['id'] = target
        del user_data['mobile']
        return user_data
コード例 #6
0
    def get(self, article_id):
        """
        获取文章详情
        :param article_id: int 文章id
        """
        # 写入埋点日志
        qs_parser = RequestParser()
        qs_parser.add_argument('Trace',
                               type=inputs.regex(r'^.+$'),
                               required=False,
                               location='headers')
        args = qs_parser.parse_args()

        user_id = g.user_id

        # 查询文章数据
        exist = cache_article.ArticleInfoCache(article_id).exists()
        if not exist:
            abort(404, message='The article does not exist.')

        article = cache_article.ArticleDetailCache(article_id).get()

        # 推荐系统所需埋点
        if args.Trace:
            write_trace_log(args.Trace, channel_id=article['ch_id'])

        article['is_followed'] = False
        article['attitude'] = None

        if user_id:
            # 非匿名用户添加用户的阅读历史
            try:
                cache_user.UserReadingHistoryStorage(user_id).save(article_id)
            except ConnectionError as e:
                current_app.logger.error(e)

            # 查询关注
            article['is_followed'] = cache_user.UserFollowingCache(
                user_id).determine_follows_target(article['aut_id'])

            # 查询登录用户对文章的态度(点赞or不喜欢)
            try:
                article['attitude'] = cache_article.ArticleUserAttitudeCache(
                    user_id, article_id).get()
            except SQLAlchemyError as e:
                current_app.logger.error(e)
                article['attitude'] = -1

        # 获取相关文章推荐
        article['recomments'] = []
        try:
            similar_articles = self._feed_similar_articles(article_id)
            for _article_id in similar_articles:
                _article = cache_article.ArticleInfoCache(_article_id).get()
                article['recomments'].append({
                    'art_id': _article['art_id'],
                    'title': _article['title']
                })
        except Exception as e:
            current_app.logger.error(e)

        # 更新阅读数
        cache_statistic.ArticleReadingCountStorage.incr(article_id)
        cache_statistic.UserArticlesReadingCountStorage.incr(article['aut_id'])

        return article