コード例 #1
0
    def get(self, request, id):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 4, 'msg': '请先登录再进行操作'})
        level = request.GET['level']
        support_levels = ['reply', 'subreply']

        if level not in support_levels:
            return JsonResponse({'code': 5, 'msg': '参数错误'})

        reply = BlogReply.objects.filter(
            pk=id)[0] if level == 'reply' else BlogSubReply.objects.filter(
                pk=id)[0]
        if reply is None:
            return JsonResponse({'code': 2, 'msg': '找不到该评论'})
        from_user_id = reply.from_user_id
        if request.user.username != from_user_id:
            return JsonResponse({'code': 3, 'msg': '你无权删除'})

        redis = get_redis()

        if level == 'reply':
            for r in reply.sub_replies.all():
                redis.delete('bsreply:{}:likes'.format(r.id))
            redis.delete('breply:{}:likes'.format(reply.id))
        else:
            redis.delete('bsreply:{}:likes'.format(reply.id))

        reply.delete()

        return JsonResponse({'code': 1, 'msg': '删除成功'})
コード例 #2
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        uid = request.GET['uid']
        redis = get_redis()
        follows_redis_key = "user:{}:follows".format(uid)
        follows = redis.smembers(follows_redis_key)
        follows_detail = []
        for follow in follows:
            follow_key = "user:{}:detail".format(follow.decode())
            follow_detail = {}
            if redis.hget(follow_key, 'username') is not None:
                follow_detail['username'] = redis.hget(follow_key,
                                                       'username').decode()
                follow_detail['nickname'] = redis.hget(follow_key,
                                                       'nickname').decode()
                follow_detail['avatar'] = redis.hget(follow_key,
                                                     'avatar').decode()
                follow_detail['bio'] = redis.hget(follow_key,
                                                  'bio').decode().replace(
                                                      '<br>', '\n')
                follow_detail['followed'] = redis.sismember(
                    "user:{}:follows".format(request.user.username),
                    follow.decode())
                follow_detail['private'] = int(
                    redis.hget(follow_key, 'private').decode())
                follows_detail.append(follow_detail)
        return JsonResponse({'code': 1, 'msg': follows_detail})
コード例 #3
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 4, 'msg': '用户尚未登录'})

        notifications = Notification.objects.filter(
            to_user_id=request.user.username).order_by('-created_at')

        notification_list = []

        if notifications:
            redis = get_redis()
            ct = ConvertTime()
            notification_list = [{
                'id': notification.id,
                'from_user_id': notification.from_user.username,
                'from_user_avatar': redis.hget('user:{}:detail'.format(notification.from_user.username), 'avatar').decode(),
                'body': notification.body,
                'app': notification.app,
                'viewed': notification.viewed,
                'created_at': ct.convertDatetime(notification.created_at)
            } for notification in notifications]

            notifications.update(viewed=True)

        return JsonResponse({'code': 1, 'msg': notification_list})
コード例 #4
0
ファイル: views.py プロジェクト: rainoceantop/xspace
    def get(self, request, id):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 4, 'msg': '修改图片请先登录'})
        try:
            photo = Photo.objects.get(pk=id)
            redis = get_redis()
            if photo.author_id == request.user.username:
                access_key = 'M2TrolxfManTFNP4Clr3M12JW0tvAaCV0xIbrZk5'
                secret_key = 'Llh0byt0KDHwiFlcNVvPiTpQSrH8IrZSt5puu1zS'

                q = qiniu_auth(access_key, secret_key)
                bucket_name = 'photo'
                try:
                    bucket = BucketManager(q)
                    key = os.path.basename(photo.url)
                    ret, info = bucket.delete(bucket_name, key)
                    assert ret == {}
                except Exception as e:
                    pass

                # 删除该博客的所有评论点赞数
                for r in photo.replies.all():
                    redis.delete('preply:{}:likes'.format(r.id))
                for r in photo.sub_replies.all():
                    redis.delete('psreply:{}:likes'.format(r.id))

                # 删除博客点赞
                redis.delete('photo:{}:likes'.format(id))

                # 删除博客
                photo.delete()
                return JsonResponse({'code': 1, 'msg': '删除成功'})
            return JsonResponse({'code': 3, 'msg': '删除失败,无权删除'})
        except exceptions.ObjectDoesNotExist:
            return JsonResponse({'code': 2, 'msg': '删除失败,没有该图片'})
コード例 #5
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        uid = request.GET['uid']
        redis = get_redis()
        redis_key = "user:{}:fans".format(uid)
        fans = redis.smembers(redis_key)
        fans_detail = []
        for fan in fans:
            fan_key = "user:{}:detail".format(fan.decode())
            fan_detail = {}
            if redis.hget(fan_key, 'username') is not None:
                fan_detail['username'] = redis.hget(fan_key,
                                                    'username').decode()
                fan_detail['nickname'] = redis.hget(fan_key,
                                                    'nickname').decode()
                fan_detail['avatar'] = redis.hget(fan_key, 'avatar').decode()
                fan_detail['bio'] = redis.hget(fan_key,
                                               'bio').decode().replace(
                                                   '<br>', '\n')
                fan_detail['followed'] = redis.sismember(
                    "user:{}:follows".format(request.user.username),
                    fan.decode())
                fan_detail['private'] = int(
                    redis.hget(fan_key, 'private').decode())
                fans_detail.append(fan_detail)

        # 如果是本人,获取关注请求
        requests_detail = []
        if uid == request.user.username:
            requests_redis_key = "user:{}:followRequests".format(uid)
            requests = redis.smembers(requests_redis_key)
            for r in requests:
                r_key = "user:{}:detail".format(r.decode())
                r_detail = {}
                if redis.hget(r_key, 'username') is not None:
                    r_detail['username'] = redis.hget(r_key,
                                                      'username').decode()
                    r_detail['nickname'] = redis.hget(r_key,
                                                      'nickname').decode()
                    r_detail['avatar'] = redis.hget(r_key, 'avatar').decode()
                    r_detail['bio'] = redis.hget(r_key,
                                                 'bio').decode().replace(
                                                     '<br>', '\n')
                    r_detail['followed'] = redis.sismember(
                        "user:{}:follows".format(request.user.username),
                        r.decode())
                    r_detail['private'] = int(
                        redis.hget(r_key, 'private').decode())
                    requests_detail.append(r_detail)
        return JsonResponse({
            'code': 1,
            'msg': {
                'fans': fans_detail,
                'requests': requests_detail
            }
        })
コード例 #6
0
    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 4, 'msg': '请先登录再进行操作'})

        data = json.loads(request.body)
        blog_id = data['id']
        reply_id = data['reply_id']
        to_reply = data['to_reply']
        body = data['body'].strip()
        to_user_id = data['to_user_id']

        if len(body) < 1 or len(body) > 1000:
            return JsonResponse({'code': 3, 'msg': '回复内容有效长度区间为[1-300]'})

        if Blog.objects.filter(id=blog_id).count() is not 1:
            return JsonResponse({'code': 5, 'msg': '找不到该博客'})

        if User.objects.filter(username=to_user_id).count() is not 1:
            return JsonResponse({'code': 6, 'msg': '所回复用户不存在'})

        sub_reply = BlogSubReply.objects.create(
            blog_id=blog_id,
            reply_id=reply_id,
            to_reply=to_reply,
            body=body,
            from_user_id=request.user.username,
            to_user_id=to_user_id)

        redis = get_redis()
        ct = ConvertTime()

        sub_reply = {
            'id':
            sub_reply.id,
            'reply_id':
            sub_reply.reply_id,
            'body':
            sub_reply.body,
            'from_user_id':
            sub_reply.from_user_id,
            'from_user_nickname':
            redis.hget("user:{}:detail".format(sub_reply.from_user_id),
                       "nickname").decode(),
            'from_user_avatar':
            redis.hget("user:{}:detail".format(sub_reply.from_user_id),
                       "avatar").decode(),
            'to_user_id':
            sub_reply.to_user_id,
            'created_at':
            ct.convertDatetime(sub_reply.created_at),
            'likes':
            0,
            'liked':
            False
        }
        return JsonResponse({'code': 1, 'msg': sub_reply})
コード例 #7
0
 def get(self, request):
     username = request.GET['username']
     user_detail = get_user_detail(username)
     if user_detail:
         redis = get_redis()
         user_detail['followed'] = redis.sismember(
             "user:{}:fans".format(username), request.user.username
         ) if request.user.is_authenticated else False
         return JsonResponse({'code': 1, 'msg': user_detail})
     return JsonResponse({'code': 2, 'msg': '找不到该用户'})
コード例 #8
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        operate = request.GET['operate']
        redis = get_redis()
        key = "user:{}:detail".format(request.user.username)
        if operate == 'open':
            redis.hset(key, 'private', 1)
        if operate == 'close':
            redis.hset(key, 'private', 0)

        return JsonResponse({'code': 1, 'msg': '操作成功'})
コード例 #9
0
ファイル: signals.py プロジェクト: rainoceantop/xspace
def create_user_detail(sender, instance, created, **kwargs):
    if created:
        user = instance
        redis = get_redis()
        redis_key = 'user:{}:detail'.format(user.username)
        redis.hmset(
            redis_key, {
                'username': user.username,
                'nickname': user.last_name,
                'avatar': 'http://pmdz71py1.bkt.clouddn.com/default.jpg',
                'bio': '',
                'website': '',
                'private': 0
            })
コード例 #10
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        redis = get_redis()
        ct = ConvertTime()
        follows = redis.smembers('user:{}:follows'.format(
            request.user.username))
        follows = [follow.decode() for follow in follows]
        follows.append(request.user.username)
        photos = Photo.objects.annotate(replies_count=Count('replies')).filter(
            author_id__in=follows).filter(
                created_at__gte=datetime.now() -
                timedelta(days=15)).prefetch_related('tags')
        blogs = Blog.objects.annotate(replies_count=Count('replies')).filter(
            author_id__in=follows).filter(
                created_at__gte=datetime.now() -
                timedelta(days=15)).prefetch_related('tags')
        moments = sorted(chain(photos, blogs),
                         key=lambda instance: instance.created_at,
                         reverse=True)
        items = []
        for r in moments:
            item = {}
            item['id'] = r.id
            item['title'] = r.title
            item['app'] = r.app
            item['author_id'] = r.author_id
            item['created_at'] = ct.convertDatetime(r.created_at)
            item['timestamp'] = ct.datetimeToTimeStamp(r.created_at)
            item['tags'] = [tag.name for tag in r.tags.all()]
            item['author'] = redis.hget("user:{}:detail".format(r.author_id),
                                        'nickname').decode()
            item['author_avatar'] = redis.hget(
                "user:{}:detail".format(r.author_id), 'avatar').decode()
            item['replies_count'] = r.replies_count
            item['replies'] = []
            if r.app == 'photo':
                item['url'] = r.url
                item['caption'] = r.caption
                item['likes'] = redis.scard('photo:{}:likes'.format(r.id))
                item['liked'] = redis.sismember('photo:{}:likes'.format(r.id),
                                                request.user.username)
            if r.app == 'blog':
                item['body'] = r.body
                item['likes'] = redis.scard('blog:{}:likes'.format(r.id))
                item['liked'] = redis.sismember('blog:{}:likes'.format(r.id),
                                                request.user.username)
            items.append(item)
        return JsonResponse({'code': 1, 'msg': items})
コード例 #11
0
ファイル: signals.py プロジェクト: rainoceantop/xspace
def add_photo_notification(sender, instance, created, **kwargs):
    if created:
        photo = instance
        redis = get_redis()
        redis_key = 'user:{}:fans'.format(photo.author_id)
        fans = redis.smembers(redis_key)
        fans = [fan.decode() for fan in fans]
        r = add_notification(one_or_many='many',
                             from_user_id=photo.author_id,
                             to_users=fans,
                             action='post',
                             body='{}发表了新图片'.format(photo.author.last_name),
                             app='photo:{}'.format(photo.id))
        print(r)
コード例 #12
0
def get_user_detail(uid):
    redis = get_redis()
    redis_key = "user:{}:detail".format(uid)
    user_detail = {
        'username': redis.hget(redis_key, 'username').decode(),
        'nickname': redis.hget(redis_key, 'nickname').decode(),
        'avatar': redis.hget(redis_key, 'avatar').decode(),
        'bio': redis.hget(redis_key, 'bio').decode(),
        'private': int(redis.hget(redis_key, 'private').decode()),
        'website': redis.hget(redis_key, 'website').decode(),
        'follows': redis.scard("user:{}:follows".format(uid)),
        'fans': redis.scard("user:{}:fans".format(uid)),
    } if redis.hget(redis_key, 'username') is not None else False
    return user_detail
コード例 #13
0
    def get(self, request):
        tag = request.GET['tag']
        page = int(request.GET['page'])
        p_from_index = 12 * (page - 1)
        b_from_index = 6 * (page - 1)
        # 探索
        if not tag:
            photos = Photo.objects.annotate(
                replies_count=Count('replies', distinct=True) +
                Count('sub_replies', distinct=True)
            ).filter(~Q(
                author_id=request.user.username))[p_from_index:p_from_index +
                                                  12]
            blogs = Blog.objects.annotate(
                replies_count=Count('replies', distinct=True) +
                Count('sub_replies', distinct=True)
            ).filter(~Q(
                author_id=request.user.username))[b_from_index:b_from_index +
                                                  6]
        else:
            photos = Photo.objects.annotate(
                replies_count=Count('replies', distinct=True) +
                Count('sub_replies', distinct=True)).filter(
                    tags__name=tag)[p_from_index:p_from_index + 12]
            blogs = Blog.objects.annotate(
                replies_count=Count('replies', distinct=True) +
                Count('sub_replies', distinct=True)).filter(
                    tags__name=tag)[b_from_index:b_from_index + 6]

        explores = chain(photos, blogs)
        if explores:
            redis = get_redis()
            items = []
            ct = ConvertTime()
            for r in explores:
                item = {}
                item['id'] = r.id
                item['app'] = r.app
                item['replies_count'] = r.replies_count
                item['timestamp'] = ct.datetimeToTimeStamp(r.created_at)
                if r.app == 'photo':
                    item['url'] = r.url
                    item['likes'] = redis.scard('photo:{}:likes'.format(r.id))
                if r.app == 'blog':
                    item['title'] = r.title
                    item['likes'] = redis.scard('blog:{}:likes'.format(r.id))
                items.append(item)
            return JsonResponse({'code': 1, 'msg': items})
        return JsonResponse({'code': 2, 'msg': '暂无数据'})
コード例 #14
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        redis = get_redis()
        redis_key = "user:{}:detail".format(request.user.username)

        data = {
            'nickname': redis.hget(redis_key, 'nickname').decode(),
            'website': redis.hget(redis_key, 'website').decode(),
            'bio': redis.hget(redis_key, 'bio').decode().replace('<br>', '\n'),
            'email': request.user.email,
            'firstname': request.user.first_name
        }
        return JsonResponse({'code': 1, 'msg': data})
コード例 #15
0
def add_blog_notification(sender, instance, created, **kwargs):
    if created:
        blog = instance
        redis = get_redis()
        redis_key = 'user:{}:fans'.format(blog.author_id)
        fans = redis.smembers(redis_key)
        fans = [fan.decode() for fan in fans]
        r = add_notification(
            one_or_many='many',
            from_user_id=blog.author_id,
            to_users=fans,
            action='post',
            body='{}发表了新博客:《{}》'.format(blog.author.last_name, blog.title),
            app='blog:{}'.format(blog.id)
        )
        print(r)
コード例 #16
0
 def get(self, request):
     searchText = request.GET['beginWith']
     users = []
     if len(searchText) is not 0:
         redis = get_redis()
         users = [{
             'username':
             user.username,
             'nickname':
             user.last_name,
             'avatar':
             redis.hget("user:{}:detail".format(user.username),
                        'avatar').decode()
         } for user in User.objects.filter(
             Q(username__startswith=searchText)
             | Q(last_name__startswith=searchText))]
     return JsonResponse({'code': 1, 'msg': users})
コード例 #17
0
    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        data = json.loads(request.body)
        nickname = data['nickname'].strip()
        website = data['website'].strip()
        bio = data['bio'].strip().replace('\n', '<br>')
        email = data['email'].strip()
        firstname = data['firstname'].strip()

        redis = get_redis()

        if len(nickname) > 20 or len(nickname) is 0:
            return JsonResponse({'code': 3, 'msg': '名称有效长度区间[1-20]'})

        if len(bio) > 150:
            return JsonResponse({'code': 3, 'msg': '个人简介有效长度区间[0-150]'})

        w_p = r"^https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+"

        if len(website) > 0 and not re.match(w_p, website):
            return JsonResponse({'code': 4, 'msg': '网址格式不正确'})

        redis.hmset('user:{}:detail'.format(request.user.username), {
            'nickname': nickname,
            'website': website,
            'bio': bio
        })

        e_p = r"^[A-Za-z0-9\.\+_-]+@[A-Za-z0-9\._-]+\.[a-zA-Z]*$"
        if len(email) > 0 and not re.match(e_p, email):
            return JsonResponse({'code': 5, 'msg': 'email格式不正确'})

        if len(firstname) > 30:
            return JsonResponse({'code': 6, 'msg': '姓名长度超出区间范围[1-30]'})

        if len(email) > 0 or len(firstname) > 0 or len(nickname) > 0:
            user = User.objects.get(pk=request.user.id)
            user.email = email
            user.first_name = firstname
            user.last_name = nickname
            user.save()
        return JsonResponse({'code': 1, 'msg': '更新成功'})
コード例 #18
0
    def get(self, request, id):
        redis = get_redis()
        ct = ConvertTime()
        try:
            blog = Blog.objects.get(pk=id)

            redis_blog_user_key = "user:{}:detail".format(blog.author_id)

            blog = {
                'id':
                blog.id,
                'author_id':
                blog.author_id,
                'title':
                blog.title,
                'body':
                blog.body,
                'tags': [tag.name for tag in blog.tags.all()],
                'created_at':
                ct.convertDatetime(blog.created_at),
                'author':
                redis.hget(redis_blog_user_key, 'nickname').decode(),
                'author_avatar':
                redis.hget(redis_blog_user_key, 'avatar').decode(),
                'author_follows':
                redis.scard("user:{}:follows".format(blog.author_id)),
                'author_fans':
                redis.scard("user:{}:fans".format(blog.author_id)),
                'replies_count':
                blog.replies.count() + blog.sub_replies.count(),
                'likes':
                redis.scard('blog:{}:likes'.format(blog.id)),
                'liked':
                redis.sismember('blog:{}:likes'.format(blog.id),
                                request.user.username)
                if request.user.is_authenticated else False
            }

            return JsonResponse({'code': 1, 'msg': blog, 'addition': ['']})
        except exceptions.ObjectDoesNotExist:
            return JsonResponse({'code': 2, 'msg': '找不到该博客'})
コード例 #19
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        uid = request.GET['uid']
        way = request.GET['way']
        redis = get_redis()

        if way == 'pass':
            # 被关注者添加粉丝
            redis.sadd('user:{}:fans'.format(request.user.username), uid)
            # 关注者添加关注
            redis.sadd('user:{}:follows'.format(uid), request.user.username)
            # 移除请求
            redis.srem('user:{}:followRequests'.format(request.user.username),
                       uid)
        else:
            # 移除请求
            redis.srem('user:{}:followRequests'.format(request.user.username),
                       uid)

        return JsonResponse({'code': 1})
コード例 #20
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 2, 'msg': '用户尚未登录'})

        redis = get_redis()
        identity = request.GET['identity']
        fOrUnf = request.GET['fOrUnf']

        if fOrUnf == 'follow':
            # 判断被关注用户是否设置了隐私账号
            if int(
                    redis.hget("user:{}:detail".format(identity),
                               'private').decode()):
                redis.sadd("user:{}:followRequests".format(identity),
                           request.user.username)
                add_notification(one_or_many='one',
                                 from_user_id=request.user.username,
                                 to_user_id=identity,
                                 action='follow',
                                 body='{}请求关注你'.format(request.user.last_name),
                                 app='user:{}'.format(request.user.username))
            else:
                redis.sadd("user:{}:follows".format(request.user.username),
                           identity)
                redis.sadd("user:{}:fans".format(identity),
                           request.user.username)
                add_notification(one_or_many='one',
                                 from_user_id=request.user.username,
                                 to_user_id=identity,
                                 action='follow',
                                 body='{}关注了你'.format(request.user.last_name),
                                 app='user:{}'.format(request.user.username))

        if fOrUnf == 'unfollow':
            redis.srem("user:{}:follows".format(request.user.username),
                       identity)
            redis.srem("user:{}:fans".format(identity), request.user.username)

        return JsonResponse({'code': 1, 'msg': '操作成功'})
コード例 #21
0
    def get(self, request):
        reply_id = request.GET['id']
        page = int(request.GET['page'])
        from_index = 10 * (page - 1)
        replies = BlogSubReply.objects.filter(
            reply_id=reply_id)[from_index:from_index + 10]
        if replies:
            redis = get_redis()
            ct = ConvertTime()
            replies = [{
                'id':
                reply.id,
                'reply_id':
                reply.reply_id,
                'body':
                reply.body,
                'from_user_id':
                reply.from_user_id,
                'from_user_nickname':
                redis.hget("user:{}:detail".format(reply.from_user_id),
                           "nickname").decode(),
                'from_user_avatar':
                redis.hget("user:{}:detail".format(reply.from_user_id),
                           "avatar").decode(),
                'to_user_id':
                reply.to_user_id,
                'created_at':
                ct.convertDatetime(reply.created_at),
                'likes':
                redis.scard('bsreply:{}:likes'.format(reply.id)),
                'liked':
                redis.sismember('bsreply:{}:likes'.format(reply.id),
                                request.user.username)
                if request.user.is_authenticated else False
            } for reply in replies]
        else:
            replies = []

        return JsonResponse({'code': 1, 'msg': replies})
コード例 #22
0
    def get(self, request, id):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 4, 'msg': '请先登录再进行操作'})
        try:
            blog = Blog.objects.get(pk=id)
            redis = get_redis()
            if blog.author_id == request.user.username:
                # 删除该博客的所有评论点赞数
                for r in blog.replies.all():
                    redis.delete('breply:{}:likes'.format(r.id))
                for r in blog.sub_replies.all():
                    redis.delete('bsreply:{}:likes'.format(r.id))

                # 删除博客点赞
                redis.delete('blog:{}:likes'.format(id))

                # 删除博客
                blog.delete()
                return JsonResponse({'code': 1, 'msg': '删除成功'})
            return JsonResponse({'code': 3, 'msg': '删除失败,无权删除'})
        except exceptions.ObjectDoesNotExist:
            return JsonResponse({'code': 2, 'msg': '删除失败,没有该博客'})
コード例 #23
0
ファイル: views.py プロジェクト: rainoceantop/xspace
    def get(self, request, id):
        try:
            photo = Photo.objects.get(pk=id)

            redis = get_redis()
            ct = ConvertTime()

            photo = {
                'id':
                photo.id,
                'author_id':
                photo.author_id,
                'url':
                photo.url,
                'title':
                photo.title,
                'caption':
                photo.caption,
                'tags': [tag.name for tag in photo.tags.all()],
                'author':
                redis.hget("user:{}:detail".format(photo.author_id),
                           "nickname").decode(),
                'author_avatar':
                redis.hget("user:{}:detail".format(photo.author_id),
                           "avatar").decode(),
                'created_at':
                ct.convertDatetime(photo.created_at),
                'replies_count':
                photo.replies.count() + photo.sub_replies.count(),
                'likes':
                redis.scard("photo:{}:likes".format(photo.id)),
                'liked':
                redis.sismember("photo:{}:likes".format(photo.id),
                                request.user.username)
                if request.user.is_authenticated else False
            }
            return JsonResponse({'code': 1, 'msg': photo})
        except exceptions.ObjectDoesNotExist:
            return JsonResponse({'code': 2, 'msg': '找不到该图片'})
コード例 #24
0
    def get(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 4, 'msg': '请先登录再进行操作'})
        way = request.GET['way']
        identity = request.GET['id']
        addOrRem = request.GET['aor']

        redis = get_redis()
        support_ways = ['blog', 'breply', 'bsreply']
        if way not in support_ways:
            return JsonResponse({'code': 2, 'msg': '出错,找不到所给参数的有效集合'})

        key = way + ':' + identity + ':likes'
        if addOrRem == 'add':
            if way == 'blog':
                blog = Blog.objects.filter(pk=identity).first()
                action = 'bloglike'
                to_user_id = blog.author_id
                body = '{}给你的博客《{}》点了个赞'.format(request.user.last_name,
                                                blog.title)
                app = 'blog:{}'.format(blog.id)
            else:
                if way == 'breply':
                    reply = BlogReply.objects.filter(pk=identity).first()
                    action = 'replylike'
                if way == 'bsreply':
                    reply = BlogSubReply.objects.filter(pk=identity).first()
                    action = 'subreplylike'
                to_user_id = reply.from_user_id
                body = '{}赞了你的评论:{}'.format(request.user.last_name, reply.body)
                app = 'blog:{}'.format(reply.blog_id)
            if not to_user_id == request.user.username:
                notification = Notification.objects.filter(
                    Q(action=action) & Q(app=app)).last()
                if notification:
                    if notification.viewed:
                        add_notification(one_or_many='one',
                                         from_user_id=request.user.username,
                                         to_user_id=to_user_id,
                                         action=action,
                                         body=body,
                                         app=app)
                    else:
                        if way == 'blog':
                            body = '{}等多人给你的博客《{}》点赞'.format(
                                request.user.last_name, blog.title)
                        else:
                            body = '{}等多人赞了你的评论:“{}”'.format(
                                request.user.last_name, reply.body)
                        notification.body = body if len(
                            body) < 150 else body[:147] + '...'
                        notification.save()
                else:
                    add_notification(one_or_many='one',
                                     from_user_id=request.user.username,
                                     to_user_id=to_user_id,
                                     action=action,
                                     body=body,
                                     app=app)
            redis.sadd(key, request.user.username)
        if addOrRem == 'rem':
            redis.srem(key, request.user.username)
        return JsonResponse({'code': 1, 'msg': '操作成功'})
コード例 #25
0
    def post(self, request):
        if not request.user.is_authenticated:
            return JsonResponse({'code': 7, 'msg': '请先登录'})

        avatar_file = request.FILES.get('avatar')
        if not avatar_file:
            return JsonResponse({'code': 2, 'msg': '请选择需要上传的图片'})

        allow_types = ['image/jpeg', 'image/png', 'image/gif']

        if avatar_file.content_type not in allow_types:
            return JsonResponse({'code': 3, 'msg': '上传失败,文件类型错误'})

        file_name = '{}_avatar_{}_{}'.format(request.user.username,
                                             time.time(), avatar_file.name)
        fs = FileSystemStorage()
        fs.save(file_name, avatar_file)
        file_path = os.path.join(MEDIA_ROOT, file_name)

        # compress the image
        i = Image.open(file_path)
        i.thumbnail((300, 300))
        i.save(file_path)

        access_key = 'M2TrolxfManTFNP4Clr3M12JW0tvAaCV0xIbrZk5'
        secret_key = 'Llh0byt0KDHwiFlcNVvPiTpQSrH8IrZSt5puu1zS'

        q = qiniu_auth(access_key, secret_key)
        bucket_name = 'avatar'
        redis = get_redis()

        try:
            token = q.upload_token(bucket_name, file_name, 3600)
            ret, info = put_file(token, file_name, file_path)
            assert ret['key'] == file_name
            assert ret['hash'] == etag(file_path)
        except Exception as e:
            return JsonResponse({'code': 4, 'msg': '上传文件出错'})
        finally:
            # 删除本地
            fs.delete(file_name)
            # 删除以前头像地址
            used_avatar = redis.hget(
                'user:{}:detail'.format(request.user.username),
                'avatar').decode()

            if used_avatar != 'http://avatar.cdn.henji.xyz/default.jpg':
                try:
                    bucket = BucketManager(q)
                    key = os.path.basename(used_avatar)
                    ret, info = bucket.delete(bucket_name, key)
                    assert ret == {}
                except Exception as e:
                    pass

            # 更新头像地址
            url = 'http://avatar.cdn.henji.xyz/{}'.format(file_name)
            redis.hset('user:{}:detail'.format(request.user.username),
                       'avatar', "{}-avatar".format(url))

            # 刷新缓存
            cdn_manager = CdnManager(q)
            urls = [url]
            cdn_manager.refresh_urls(urls)

            return JsonResponse({'code': 1, 'msg': url})