Exemple #1
0
    def get(self, event):
        """
        im测试
        """
        user_id = 1
        if 'f' == event:
            target = 5
            # 发送关注通知
            _user = cache_user.UserProfileCache(user_id).get()
            _data = {
                'user_id': user_id,
                'user_name': _user['name'],
                'user_photo': _user['photo'],
                'timestamp': int(time.time())
            }
            current_app.sio.emit('following notify',
                                 data=_data,
                                 room=str(target))

            return {'message': '已发送following notify事件'}

        elif 'l' == event:
            target = 141428
            # 发送点赞通知
            _user = cache_user.UserProfileCache(user_id).get()
            _article = cache_article.ArticleInfoCache(target).get()
            _data = {
                'user_id': user_id,
                'user_name': _user['name'],
                'user_photo': _user['photo'],
                'art_id': target,
                'art_title': _article['title'],
                'timestamp': int(time.time())
            }
            current_app.sio.emit('liking notify',
                                 data=_data,
                                 room=str(_article['aut_id']))
            return {'message': '已发送liking notify事件'}

        elif 'c' == event:
            article_id = 141428
            # 发送评论通知
            _user = cache_user.UserProfileCache(user_id).get()
            _article = cache_article.ArticleInfoCache(article_id).get()
            _data = {
                'user_id': user_id,
                'user_name': _user['name'],
                'user_photo': _user['photo'],
                'art_id': article_id,
                'art_title': _article['title'],
                'timestamp': int(time.time())
            }
            current_app.sio.emit('comment notify',
                                 data=_data,
                                 room=str(_article['aut_id']))
            return {'message': '已发送comment notify事件'}

        else:
            return {'message': '错误的事件'}, 404
Exemple #2
0
    def get(self, user_id):
        """
        获取user_id 用户的文章数据
        """
        exist = cache_user.UserProfileCache(user_id).exists()
        if not exist:
            return {'message': 'Invalid request.'}, 400
        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_ARTICLE_PER_PAGE_MIN,
                                                                 constants.DEFAULT_ARTICLE_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_ARTICLE_PER_PAGE_MIN

        results = []

        total_count, page_articles = cache_user.UserArticlesCache(user_id).get_page(page, per_page)

        for article_id in page_articles:
            article = cache_article.ArticleInfoCache(article_id).get()
            if article:
                results.append(article)

        return {'total_count': total_count, 'page': page, 'per_page': per_page, 'results': results}
Exemple #3
0
    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}
Exemple #4
0
    def patch(self):
        file_parser = RequestParser()
        file_parser.add_argument('photo',
                                 type=parser.image_file,
                                 required=False,
                                 location='files')
        files = file_parser.parse_args()

        user_id = g.user_id
        new_cache_values = {}
        new_user_values = {}
        return_values = {'id': user_id}

        if files.photo:
            try:
                photo_url = upload_image(files.photo.read())
            except Exception as e:
                current_app.logger.error('upload failed {}'.format(e))
                return {
                    'message': 'Uploading profile photo image failed.'
                }, 507
            new_cache_values['photo'] = photo_url
            new_user_values['profile_photo'] = photo_url
            return_values[
                'photo'] = current_app.config['QINIU_DOMAIN'] + photo_url

        if new_user_values:
            User.query.filter_by(id=user_id).update(new_user_values)

        db.session.commit()

        if new_cache_values:
            cache_user.UserProfileCache(user_id).clear()

        return return_values, 201
Exemple #5
0
 def get(self):
     """
     获取当前用户自己的数据
     """
     user_data = cache_user.UserProfileCache(g.user_id).get()
     user_data['id'] = g.user_id
     del user_data['mobile']
     return user_data
Exemple #6
0
    def post(self):
        """
        文章点赞
        """
        json_parser = RequestParser()
        json_parser.add_argument('target',
                                 type=parser.article_id,
                                 required=True,
                                 location='json')
        args = json_parser.parse_args()
        target = args.target

        # 此次操作前,用户对文章可能是没有态度,也可能是不喜欢,需要先查询对文章的原始态度,然后对相应的统计数据进行累计或减少
        atti = Attitude.query.filter_by(user_id=g.user_id,
                                        article_id=target).first()
        if atti is None:
            attitude = Attitude(user_id=g.user_id,
                                article_id=target,
                                attitude=Attitude.ATTITUDE.LIKING)
            db.session.add(attitude)
            db.session.commit()
            cache_statistic.ArticleLikingCountStorage.incr(target)
        else:
            if atti.attitude == Attitude.ATTITUDE.DISLIKE:
                # 原先是不喜欢
                atti.attitude = Attitude.ATTITUDE.LIKING
                db.session.add(atti)
                db.session.commit()
                cache_statistic.ArticleLikingCountStorage.incr(target)
                cache_statistic.ArticleDislikeCountStorage.incr(target, -1)
                cache_statistic.UserLikedCountStorage.incr(g.user_id)
            elif atti.attitude is None:
                # 存在数据,但是无态度
                atti.attitude = Attitude.ATTITUDE.LIKING
                db.session.add(atti)
                db.session.commit()
                cache_statistic.ArticleLikingCountStorage.incr(target)
                cache_statistic.UserLikedCountStorage.incr(g.user_id)

        # cache_article.ArticleUserAttitudeCache(g.user_id, target).clear()
        cache_user.UserArticleAttitudeCache(g.user_id).clear()

        # 发送点赞通知
        _user = cache_user.UserProfileCache(g.user_id).get()
        _article = cache_article.ArticleInfoCache(target).get()
        _data = {
            'user_id': g.user_id,
            'user_name': _user['name'],
            'user_photo': _user['photo'],
            'art_id': target,
            'art_title': _article['title'],
            'timestamp': int(time.time())
        }
        current_app.sio.emit('liking notify',
                             data=_data,
                             room=str(_article['aut_id']))

        return {'target': target}, 201
Exemple #7
0
 def fill_fields(cls, comment):
     """
     补充字段
     :param comment:
     :return:
     """
     _user = cache_user.UserProfileCache(comment['aut_id']).get()
     comment['aut_name'] = _user['name']
     comment['aut_photo'] = _user['photo']
     comment['like_count'] = cache_statistic.CommentLikingCountStorage.get(comment['com_id'])
     comment['reply_count'] = cache_statistic.CommentReplyCountStorage.get(comment['com_id'])
     return comment
Exemple #8
0
 def _fill_fields(self, article_formatted):
     """
     补充字段
     """
     article_formatted['art_id'] = self.article_id
     # 获取作者名
     author = cache_user.UserProfileCache(article_formatted['aut_id']).get()
     article_formatted['aut_name'] = author['name']
     article_formatted['comm_count'] = cache_statistic.ArticleCommentCountStorage.get(self.article_id)
     article_formatted['like_count'] = cache_statistic.ArticleLikingCountStorage.get(self.article_id)
     article_formatted['collect_count'] = cache_statistic.ArticleCollectingCountStorage.get(self.article_id)
     return article_formatted
Exemple #9
0
    def patch(self):
        """
        编辑用户的信息
        """
        db.session().set_to_write()
        json_parser = RequestParser()
        json_parser.add_argument('name',
                                 type=inputs.regex(r'^.{1,7}$'),
                                 required=False,
                                 location='json')
        json_parser.add_argument('intro',
                                 type=inputs.regex(r'^.{0,60}$'),
                                 required=False,
                                 location='json')
        json_parser.add_argument('email',
                                 type=parser.email,
                                 required=False,
                                 location='json')
        args = json_parser.parse_args()

        user_id = g.user_id
        new_cache_values = {}
        new_user_values = {}
        return_values = {'id': user_id}

        if args.name:
            new_cache_values['name'] = args.name
            new_user_values['name'] = args.name
            return_values['name'] = args.name

        if args.intro:
            new_cache_values['intro'] = args.intro
            new_user_values['introduction'] = args.intro
            return_values['intro'] = args.intro

        if args.email:
            # TODO email 缓存
            new_user_values['email'] = args.email
            return_values['email'] = args.email

        try:
            if new_user_values:
                User.query.filter_by(id=user_id).update(new_user_values)
        except IntegrityError:
            db.session.rollback()
            return {'message': 'User name has existed.'}, 409

        db.session.commit()
        if new_cache_values:
            cache_user.UserProfileCache(user_id).clear()

        return return_values, 201
Exemple #10
0
    def post(self):
        """
        登录创建token
        """
        json_parser = RequestParser()
        json_parser.add_argument('mobile', type=parser.mobile, required=True, location='json')
        json_parser.add_argument('code', type=parser.regex(r'^\d{6}$'), required=True, location='json')
        args = json_parser.parse_args()
        mobile = args.mobile
        code = args.code

        # 从redis中获取验证码
        key = 'app:code:{}'.format(mobile)
        try:
            real_code = current_app.redis_master.get(key)
        except ConnectionError as e:
            current_app.logger.error(e)
            real_code = current_app.redis_slave.get(key)

        if mobile != '18516952650':
            try:
                current_app.redis_master.delete(key)
            except ConnectionError as e:
                current_app.logger.error(e)

        if not real_code or real_code.decode() != code:
            return {'message': 'Invalid code.'}, 400

        # 查询或保存用户
        user = User.query.filter_by(mobile=mobile).first()

        if user is None:
            # 用户不存在,注册用户
            user_id = current_app.id_worker.get_id()
            user = User(id=user_id, mobile=mobile, name=mobile, last_login=datetime.now())
            db.session.add(user)
            profile = UserProfile(id=user.id)
            db.session.add(profile)
            db.session.commit()
        else:
            if user.status == User.STATUS.DISABLE:
                cache_user.UserStatusCache(user.id).save(user.status)
                return {'message': 'Invalid user.'}, 403

        token, refresh_token = self._generate_tokens(user.id)

        # 缓存用户信息
        cache_user.UserProfileCache(user.id).save()
        cache_user.UserStatusCache(user.id).save(User.STATUS.ENABLE)
        return {'token': token, 'refresh_token': refresh_token}, 201
Exemple #11
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
Exemple #12
0
 def get(self):
     """
     获取用户资料
     """
     user_id = g.user_id
     user = cache_user.UserProfileCache(user_id).get()
     result = {
         'id': user_id,
         'name': user['name'],
         'photo': user['photo'],
         'mobile': user['mobile']
     }
     # 补充性别生日等信息
     result.update(cache_user.UserAdditionalProfileCache(user_id).get())
     return result
Exemple #13
0
    def get(self, user_id):

        # 检验参数
        cache_tool = cache_user.UserProfileCache(user_id)
        if not cache_tool.exists():
            # 用户不存在
            return {'message': 'User does not exists.'}, 404
        else:
            # {
            # 	"message": "OK",
            # 	"data": {
            # 		"user_id": xx,
            # 		"name": xx,
            # 		"photo":xx,
            # 		"intro": xx,
            # 		"certi": xx,
            # 		"artile_count": xx,
            # 		"follows_count": xx,
            # 		"fans_count": xx,
            # 		"liking_count": xx
            # 	}
            # }

            # 查询用户数据
            user_dict = cache_tool.get()
            user_dict['user_id'] = user_id
            user_dict['photo'] = current_app.config[
                'QINIU_DOMAIN'] + user_dict['photo']

            del user_dict['mobile']

            user_dict[
                'article_count'] = cache_statistic.UserArtuclesCountStorage.get(
                    user_id)
            user_dict[
                'follows_count'] = cache_statistic.UserFollowsCountStorage.get(
                    user_id)
            user_dict['fans_count'] = cache_statistic.UserFansCountStorage.get(
                user_id)
            user_dict[
                'liking_count'] = cache_statistic.UserLikingCountStorage.get(
                    user_id)

            return user_dict
Exemple #14
0
def user_id(value):
    """
    检查是否是user_id
    :param value: 被检验的值
    :return: user_id
    """
    try:
        _user_id = int(value)
    except Exception:
        raise ValueError('Invalid target user id.')
    else:
        if _user_id <= 0:
            raise ValueError('Invalid target user id.')
        else:
            ret = cache_user.UserProfileCache(_user_id).exists()
            if ret:
                return _user_id
            else:
                raise ValueError('Invalid target user id.')
Exemple #15
0
    def get(self):
        """
        获取文章详情信息
        :return:
        """
        # 查询文章数据
        rc = current_app.redis_cluster
        try:
            article_bytes = rc.get(self.key)
        except RedisError as e:
            current_app.logger.error(e)
            article_bytes = None

        if article_bytes:
            # 使用缓存
            article_dict = json.loads(article_bytes)
        else:
            # 查询数据库
            article = Article.query.options(load_only(
                Article.id,
                Article.user_id,
                Article.title,
                Article.is_advertising,
                Article.ctime,
                Article.channel_id
            )).filter_by(id=self.article_id, status=Article.STATUS.APPROVED).first()

            article_dict = marshal(article, self.article_fields)

            # 缓存
            article_cache = json.dumps(article_dict)
            try:
                rc.setex(self.key, constants.ArticleDetailCacheTTL.get_val(), article_cache)
            except RedisError:
                pass

        user = cache_user.UserProfileCache(article_dict['aut_id']).get()

        article_dict['aut_name'] = user['name']
        article_dict['aut_photo'] = user['photo']

        return article_dict
Exemple #16
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
        user_data['is_blacklist'] = False
        if g.user_id:
            relation_cache = cache_user.UserRelationshipCache(g.user_id)
            user_data['is_following'] = relation_cache.determine_follows_target(target)
            user_data['is_blacklist'] = relation_cache.determine_blacklist_target(target)

        user_data['id'] = target
        del user_data['mobile']
        return user_data
Exemple #17
0
    def get(self, user_id):
        # 校验参数
        cache_tool = cache_user.UserProfileCache(user_id)
        if not cache_tool.exists():
            # 用户不存在
            return {'message': 'User does not exits.'}, 400

        # 业务处理
        # 查询用户信息
        user_dict = cache_tool.get()

        # {
        # 			"user_id": xx,
        # 			"name": xx,
        # 			"photo": xx,
        # 			"intro": xx,
        # 			"certi": xxx,
        # 			"article_count": xxx,
        # 			"follows_count": xxx,
        # 			"fans_count": xx,
        # 			"liking_count": xxx
        # 		}
        del user_dict['mobile']
        user_dict['user_id'] = user_id

        user_dict[
            'article_count'] = cache_statistic.UserArticlesCountStorage.get(
                user_id)
        user_dict[
            'follows_count'] = cache_statistic.UserFollowingsCountStorage.get(
                user_id)
        user_dict[
            'fans_count'] = cache_statistic.UserFollowersCountStorage.get(
                user_id)
        user_dict['liking_count'] = cache_statistic.UserLikedCountStorage.get(
            user_id)

        # 返回
        return user_dict
Exemple #18
0
    def get(self, user_id):
        # 接受
        # 校验
        cache_tool = cache_user.UserProfileCache(user_id)
        if not cache_tool.determine_user_exists():
            # 用户不存在
            return {'message': 'User does not exits'}, 400
        # 处理
        user_dict = cache_tool.get()
        # 可获得参数
        #       'mobile': user.mobile,
        #       'name': user.name,
        #       'photo': user.profile_photo,
        #       'intro': user.introduction,
        #       'certi': user.certificate
        # 需要返回的数据
        # 	    "user_id": xx,
        # 		"name": xx,
        # 		"photo": xx,
        # 		"intro": xx,
        # 		"certi": xxx,
        # 		"article_count": xxx,
        # 		"follows_count": xxx,
        # 		"fans_count": xx,
        # 		"liking_count": xxx
        # 依据以上修改构建返回数据
        del user_dict['mobile']
        user_dict['user_id'] = user_id
        user_dict['photo'] = current_app.config['QINIU_DOMAIN'] + user_dict['photo']

        user_dict['article_count'] = cache_stastistic.UserArticlesCountStorage.get(user_id)
        user_dict['follows_count'] = cache_stastistic.UserFollowingsCountStorage.get(user_id)
        user_dict['fans_count'] = cache_stastistic.UserFansCountStorage.get(user_id)
        user_dict['liking_count'] = cache_stastistic.UserLikingCountStorage.get(user_id)

        # 返回
        return user_dict
Exemple #19
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
Exemple #20
0
    def patch(self):
        """
        编辑用户的信息
        """
        json_parser = RequestParser()
        json_parser.add_argument('name',
                                 type=inputs.regex(r'^.{1,7}$'),
                                 required=False,
                                 location='json')
        json_parser.add_argument('photo',
                                 type=parser.image_base64,
                                 required=False,
                                 location='json')
        json_parser.add_argument('gender',
                                 type=self._gender,
                                 required=False,
                                 location='json')
        json_parser.add_argument('birthday',
                                 type=parser.date,
                                 required=False,
                                 location='json')
        json_parser.add_argument('intro',
                                 type=inputs.regex(r'^.{0,60}$'),
                                 required=False,
                                 location='json')
        json_parser.add_argument('real_name',
                                 type=inputs.regex(r'^.{1,7}$'),
                                 required=False,
                                 location='json')
        json_parser.add_argument('id_number',
                                 type=parser.id_number,
                                 required=False,
                                 location='json')
        json_parser.add_argument('id_card_front',
                                 type=parser.image_base64,
                                 required=False,
                                 location='json')
        json_parser.add_argument('id_card_back',
                                 type=parser.image_base64,
                                 required=False,
                                 location='json')
        json_parser.add_argument('id_card_handheld',
                                 type=parser.image_base64,
                                 required=False,
                                 location='json')
        args = json_parser.parse_args()

        user_id = g.user_id
        new_user_values = {}
        new_profile_values = {}
        return_values = {'id': user_id}

        need_delete_profilex = False
        need_delete_profile = False

        if args.name:
            new_user_values['name'] = args.name
            return_values['name'] = args.name
            need_delete_profile = True

        if args.photo:
            try:
                photo_url = upload(args.photo)
            except Exception as e:
                current_app.logger.error('upload failed {}'.format(e))
                return {
                    'message': 'Uploading profile photo image failed.'
                }, 507
            new_user_values['profile_photo'] = photo_url
            return_values[
                'photo'] = current_app.config['QINIU_DOMAIN'] + photo_url
            need_delete_profile = True

        if args.gender:
            new_profile_values['gender'] = args.gender
            return_values['gender'] = args.gender
            need_delete_profilex = True

        if args.birthday:
            new_profile_values['birthday'] = args.birthday
            return_values['birthday'] = args.birthday.strftime('%Y-%m-%d')
            need_delete_profilex = True

        if args.intro:
            new_user_values['introduction'] = args.intro
            return_values['intro'] = args.intro
            need_delete_profile = True

        if args.real_name:
            new_profile_values['real_name'] = args.real_name
            return_values['real_name'] = args.real_name

        if args.id_number:
            new_profile_values['id_number'] = args.id_number
            return_values['id_number'] = args.id_number

        if args.id_card_front:
            try:
                id_card_front_url = upload(args.id_card_front)
            except Exception as e:
                current_app.logger.error('upload failed {}'.format(e))
                return {
                    'message': 'Uploading id_card_front image failed.'
                }, 507
            new_profile_values['id_card_front'] = id_card_front_url
            return_values['id_card_front'] = current_app.config[
                'QINIU_DOMAIN'] + id_card_front_url

        if args.id_card_back:
            try:
                id_card_back_url = upload(args.id_card_back)
            except Exception as e:
                current_app.logger.error('upload failed {}'.format(e))
                return {'message': 'Uploading id_card_back image failed.'}, 507
            new_profile_values['id_card_back'] = id_card_back_url
            return_values['id_card_back'] = current_app.config[
                'QINIU_DOMAIN'] + id_card_back_url

        if args.id_card_handheld:
            try:
                id_card_handheld_url = upload(args.id_card_handheld)
            except Exception as e:
                current_app.logger.error('upload failed {}'.format(e))
                return {
                    'message': 'Uploading id_card_handheld image failed.'
                }, 507
            new_profile_values['id_card_handheld'] = id_card_handheld_url
            return_values['id_card_handheld'] = current_app.config[
                'QINIU_DOMAIN'] + id_card_handheld_url

        try:
            if new_user_values:
                User.query.filter_by(id=user_id).update(new_user_values)
            if new_profile_values:
                UserProfile.query.filter_by(
                    id=user_id).update(new_profile_values)
            db.session.commit()
        except IntegrityError:
            db.session.rollback()
            return {'message': 'User name has existed.'}, 409

        if need_delete_profile:
            cache_user.UserProfileCache(user_id).clear()

        if need_delete_profilex:
            cache_user.UserAdditionalProfileCache(user_id).clear()

        return return_values, 201
Exemple #21
0
    def post(self):
        """
        创建评论
        """
        json_parser = RequestParser()
        json_parser.add_argument('target',
                                 type=positive,
                                 required=True,
                                 location='json')
        json_parser.add_argument('content', required=True, location='json')
        json_parser.add_argument('art_id',
                                 type=parser.article_id,
                                 required=False,
                                 location='json')

        args = json_parser.parse_args()
        target = args.target
        content = args.content
        article_id = args.art_id

        if not content:
            return {'message': 'Empty content.'}, 400

        allow_comment = cache_article.ArticleInfoCache(
            article_id or target).determine_allow_comment()
        if not allow_comment:
            return {'message': 'Article denied comment.'}, 400

        if not article_id:
            # 对文章评论
            article_id = target

            comment_id = current_app.id_worker.get_id()
            comment = Comment(id=comment_id,
                              user_id=g.user_id,
                              article_id=article_id,
                              parent_id=None,
                              content=content)
            db.session.add(comment)
            db.session.commit()

            # TODO 增加评论审核后 在评论审核中添加缓存
            cache_statistic.ArticleCommentCountStorage.incr(article_id)
            try:
                cache_comment.CommentCache(comment_id).save(comment)
            except SQLAlchemyError as e:
                current_app.logger.error(e)
            cache_comment.ArticleCommentsCache(article_id).add(comment)

            # 发送评论通知
            _user = cache_user.UserProfileCache(g.user_id).get()
            _article = cache_article.ArticleInfoCache(article_id).get()
            _data = {
                'user_id': g.user_id,
                'user_name': _user['name'],
                'user_photo': _user['photo'],
                'art_id': article_id,
                'art_title': _article['title'],
                'timestamp': int(time.time())
            }
            current_app.sio.emit('comment notify',
                                 data=_data,
                                 room=str(_article['aut_id']))

        else:
            # 对评论的回复
            exists = cache_comment.CommentCache(target).exists()
            if not exists:
                return {'message': 'Invalid target comment id.'}, 400

            comment_id = current_app.id_worker.get_id()
            comment = Comment(id=comment_id,
                              user_id=g.user_id,
                              article_id=article_id,
                              parent_id=target,
                              content=content)
            db.session.add(comment)
            db.session.commit()

            # TODO 增加评论审核后 在评论审核中添加评论缓存
            cache_statistic.ArticleCommentCountStorage.incr(article_id)
            cache_statistic.CommentReplyCountStorage.incr(target)
            try:
                cache_comment.CommentCache(comment_id).save(comment)
            except SQLAlchemyError as e:
                current_app.logger.error(e)
            cache_comment.CommentRepliesCache(target).add(comment)

        return {
            'com_id': comment.id,
            'target': target,
            'art_id': article_id
        }, 201