Beispiel #1
0
 def put(self, request):
     serializer = CartSerializer(data=request.data)
     serializer.is_valid(raise_exception=True)
     sku_id = serializer.data.get('sku_id')
     count = serializer.data.get('count')
     selected = serializer.data.get('selected')
     try:
         user = request.user
     except Exception:
         user = None
     if user is not None and user.is_authenticated:
         redis_conn = get_redis_connection('cart')
         redis_conn.hset('cart_%s' % user.id, sku_id, count)
         if selected:
             redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
         else:
             redis_conn.srem('cart_selected_%s' % user.id, sku_id)
         return Response(serializer.data)
     else:
         cookie_str = request.COOKIES.get('cart')
         if cookie_str is not None:
             cart = pickle.loads(base64.b64decode(cookie_str))
         else:
             cart = {}
         if sku_id in cart:
             cart[sku_id] = {'count': count, 'selected': selected}
         new_cookie = base64.b64encode(pickle.dumps(cart)).decode()
         response = Response(serializer.data)
         response.set_cookie('cart', new_cookie)
         return response
Beispiel #2
0
    def put(self, request):
        """
        修改购物车
        :return:
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get("sku_id")
        count = serializer.validated_data.get("count")
        selected = serializer.validated_data.get("selected")

        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败,用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录用redis保存
            redis_con = get_redis_connection("cart")
            pl = redis_con.pipeline()
            # 记录购物车商品数量
            pl.hset("cart_%s" % user.id, sku_id, count)

            # 勾选
            if selected:
                pl.sadd("cart_selected_%s" % user.id, sku_id)

            else:
                pl.srem("cart_selected_%s" % user.id, sku_id)

            pl.execute()
            return Response(serializer.data)

        else:
            # 用户未登录
            cart = request.COOKIES.get("cart")
            if cart is not None:
                # 使用pickle序列化购物车数据, pickle操作的是bytes类型的数据
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            sku = cart.get(sku_id)
            if sku:
                count += int(sku.get('count'))

            cart[sku_id] = {"count": count, "selected": selected}

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            # 设置购物车的cookie
            # 需要设置有效期,否则是临时cookie
            response.set_cookie("cart",
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #3
0
    def post(self, request):
        """
        购物车记录添加
        """
        # 1. 获取参数(sku_id, count, selected)并进行参数校验
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 获取登录用户
        try:
            user = request.user
        except Exception as e:
            user = None

        if user and user.is_authenticated:
            # 2. 保存用户的购物车记录
            redis_conn = get_redis_connection('cart')
            pipeline = redis_conn.pipeline()
            cart_key = 'cart_%s' % user.id

            # 保存购物车中商品及数量
            pipeline.hincrby(cart_key, sku_id, count)

            # 保存购物车中商品的选中状态
            cart_selected_key = 'cart_selected_%s' % user.id
            if selected:
                pipeline.sadd(cart_selected_key, sku_id)

            pipeline.execute()

            # 3. 返回应答,保存购物车记录成功
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 获取客户端发送的cookie信息
            cookie_cart = request.COOKIES.get('cart')

            if cookie_cart:
                # 对cookie数据进行解析
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                count += cart_dict[sku_id]['count']

            cart_dict[sku_id] = {'count': count, 'selected': selected}

            # 对cart_dict数据进行处理
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)
            response.set_cookie('cart',
                                cart_data,
                                max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #4
0
    def put(self,request):
        """修改购物车中的商品"""

        # 创建序列化器,校验请求参数是否合法
        s = CartSerializer(data=request.data)
        s.is_valid(raise_exception=True)

        # 获取校验后的3个参数: sku_id, count, selected
        sku_id = s.validated_data.get('sku_id')
        count = s.validated_data.get('count')
        selected = s.validated_data.get('selected')

        # 获取用户对象: AnnomousUser
        user = request.user

        # 判断是否已经登录
        if user.is_authenticated():  # 已登录
            # cart_1 = {1: 2, 2: 2}
            # cart_selected_1 = {1,  2}  # set
            # 用户已登录,获取操作Redis的StrictRedis对象
            strict_redis = get_redis_connection('carts')  # type: StrictRedis

            pipeline = strict_redis.pipeline()
            # 修改商品数量
            pipeline.hset('cart_%s' % user.id, sku_id, count)
            # 修改商品的勾选状态
            if selected:  # 往set中添加成员
                pipeline.sadd('cart_selected_%s' % user.id, sku_id)
            else:  # 从set中删除成员
                pipeline.srem('cart_selected_%s' % user.id, sku_id)
            pipeline.execute()

            # 响应序列化数据
            return Response(s.data)

        else:  # 未登录
            # 1. 从cookie中获取购物车信息
            cart = request.COOKIES.get('cart')

            # 2. base64字符串 -> 字典
            #    {1: {'count':2, 'selected':False}, 2: {'count':2, 'selected':False}}
            if cart is None:
                cart = {}
            else:
                cart = pickle.loads(base64.b64decode(cart.encode()))

            # 3. 修改字典中对应的商品数量和选中状态
            cart[sku_id] = {
                'count': count,
                'selected': selected,
            }

            # 4. 字典 --> base64字符串
            cart_cookie = base64.b64encode(pickle.dumps(cart)).decode()

            # 5. 通过cookie保存购物车数据(base64字符串): response.set_cookie()
            response = Response(s.data)
            response.set_cookie('cart', cart_cookie, 60 * 60 * 24 * 365)  # 有效期: 1年
            # 6. 响应序列化数据
            return response
Beispiel #5
0
    def post(self, request):
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        sku_id = serializer.data.get('sku_id')
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')

        try:
            user = request.user
        except Exception:
            user = None
        # 判断用户是否登陆
        # 如果登陆并通过验证 将数据保存在redis中
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            # redis_conn.hset('cart_%s'%user.id,sku_id,count)
            # 累加
            # redis_conn.hincrby('cart_%s'%user.id,sku_id,count)
            #
            # if selected:
            #     redis_conn.sadd('cart_selected_%s'%user.id,sku_id)
            #     return Response(serializer.data)

            # redis管道
            pl = redis_conn.pipeline()
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)

        # 未登录保存在cookies中
        else:
            cookie_str = request.COOKIES.get('cart')
            # 如果有cookie 解密
            if cookie_str is not None:
                bytes_data = base64.b64decode(cookie_str)
                cookie_cart = pickle.loads(bytes_data)
            # 如果没有 cookie
            else:
                cookie_cart = {}

            #         cookie_cart = {1:{'count':2,'selected':True}}
            # 如果有则把前段传过来的个数累加
            if sku_id in cookie_cart:
                original_count = cookie_cart[sku_id]['count']
                count += original_count

            # 更新数据
            cookie_cart[sku_id] = {'count': count, 'selected': selected}

            # 加密
            bytes_dumps = pickle.dumps(cookie_cart)
            bytes_str = base64.b64encode(bytes_dumps)
            cookie_save_str = bytes_str.decode()
            # 设置cookie
            response = Response(serializer.data)
            response.set_cookie('cart', cookie_save_str, 3600)
            return response
Beispiel #6
0
    def post(self, request):
        """
        添加购物车
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败,用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 记录购物车的勾选项
            if selected:
                pl.sadd('cart_select_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 用户未登录,在cookie中保存
            # {
            #     1001: { "count": 10, "selected": true},
            #     ...
            # }
            # 使用pickle序列化购物车数据,pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = myjson.loads(cart)
            else:
                cart = {}

            sku = cart.get(sku_id)
            if sku:
                cart_count = int(sku.get('count'))
            else:
                cart_count = 0

            cart[sku_id] = {'count': count + cart_count, 'selected': selected}

            cookie_cart = myjson.dumps(cart)
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            # 设置购物车的cookie
            # 需要设置有效期, 否则是临时cookie
            response.set_cookie('cart',
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #7
0
    def put(self, request):
        """修改购物车数据"""
        # sku_id, count, selected
        # 校验
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 判断用户是否登录
        try:
            user = request.user
        except Exception:
            user = None
        if user and user.is_authenticated:
            # 已登录,查询 修改 redis
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 处理count
            pl.hset('cart_%s' % user.id, sku_id, count)
            # 处理 selected 状态
            if selected:
                # 表示勾选
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                # 取消勾选
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            # 序列化返回
            return Response(serializer.data)

        else:
            # 未登录,查询 修改 cookie
            cart_cookie = request.COOKIES.get('cart')
            if cart_cookie:
                # 表示cookie中有购物车数据
                # 解析
                cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))
            else:
                # 表示 cookie 中没有购物车数据
                cart_dict = {}

            response = Response(serializer.data)

            # 修改 cookie 中的cart数据
            if sku_id in cart_dict:
                # 存在购物车数据, 进行修改
                cart_dict['sku_id'] = {
                    'count': count,
                    'selected': selected
                }
                cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode()

                # 序列化返回
                # 设置cookie
                response.set_cookie('cart', cart_cookie, max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #8
0
    def post(self, request):
        """添加商品到购物车"""
        # 调用序列化器校验数据
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 判断用户登陆状态
        try:
            user = request.user
        except Exception:
            user = None

        # 如果已登陆,将数据保存至redis
        if user and user.is_authenticated:
            # 连接数据库
            redis = get_redis_connection('cart')

            pl = redis.pipeline()

            # 保存商品sku_id及数量
            pl.hincrby("cart_%s" % user.id, sku_id, count)
            # 保存商品勾选状态
            pl.sadd("cart_selected_%s" % user.id, sku_id)
            pl.execute()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        # 如果未登录,则将商品信息保存在cookie
        else:
            # 获取cookie中购物车数据
            cart = request.COOKIES.get('cart')
            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            # 添加购物信息
            sku_dict = cart.get(sku_id)
            if sku_dict:
                count += int(sku_dict["count"])
            cart[sku_id] = {
                "count": count,
                "selected": selected,
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)
            response.set_cookie("cart",
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRE)
            return response
Beispiel #9
0
    def put(self, request):
        data = request.data
        serializer = CartSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.data['sku_id']
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')

        try:
            user = request.user
        except Exception as e:
            user = None
            # request.user.is_authenticated
        if user is not None and user.is_authenticated:
            #登录用户从redis获取数据
            redis_conn = get_redis_connection('cart')
            #管道 提升程序运行效率
            # pl = redis_conn.pipeline()
            # #更新数据
            # pl.hset('cart_%s'%user.id,sku_id,count)
            # if selected:
            #     pl.srem('cart_selected_%s'%user.id,sku_id)
            # else:
            #     pl.srem('cart_selected_%s'%user.id,sku_id)
            # pl.execute()
            #更新数据 hash
            redis_conn.hset('cart_%s' % user.id, sku_id, count)
            #set
            if selected:
                redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('cart_selected_%s' % user.id, sku_id)

            return Response(serializer.data)
        else:
            #未登录用户cookie中获取数据
            cart_str = request.COOKIES.get('cart')
            if cart_str is not None:
                cart = pickle.loads(base64.b64decode(cart_str))
            else:
                cart = {}
            if sku_id in cart:
                cart[sku_id] = {'count': count, 'selected': selected}
            cookie_str = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)
            response.set_cookie('cart', cookie_str)

            return response
Beispiel #10
0
    def post(self, request):
        """添加购物车"""
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')
        """尝试对请求的用户进行验证"""
        try:
            user = request.user
        except Exception:
            # 验证失败,用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录, 在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)

            pl.execute()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        else:
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            sku = cart.get(sku_id)
            if sku:
                count += int(sku.get('count'))

            cart[sku_id] = {'count': count, 'selected': selected}

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            response.set_cookie('cart',
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRES)

            return response
Beispiel #11
0
    def put(self, request):
        #1.接收数据,进行数据的校验
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        #2.获取sku_id,count,selected 的值
        sku_id = serializer.data.get('sku_id')
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')

        #3.获取用户信息,进行判断
        try:
            user = request.user
        except Exception:
            user = None
        if user is not None and user.is_authenticated:
            #4.登录用户redis
            #4.1连接redis
            redis_conn = get_redis_connection('cart')
            #4.2更新数据
            redis_conn.hset('cart_%s' % user.id, sku_id, count)
            #set
            #选中状态
            if selected:
                redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                #未选中
                redis_conn.srem('cart_%s' % user.id, sku_id)
            #4.3返回数据(要将最终的商品数据返回回去)
            return Response(serializer.data)

        else:
            #5.未登录用户 cookie
            #5.1读取cookie,并判断数据是否存在
            cookie_str = request.COOKIES.get('cart')
            if cookie_str is not None:
                #读取数据
                cart = pickle.loads(base64.b64decode(cookie_str))
            else:
                cart = {}
            #5.2更新数据
            if sku_id in cart:
                cart[sku_id] = {'count': count, 'selected': selected}
            #5.3对字典进行处理
            new_cookie = base64.b64encode(pickle.dumps(cart)).decode()
            #5.4返回响应
            response = Response(serializer.data)
            response.set_cookie('cart', new_cookie)
            return response
Beispiel #12
0
    def put(self, request):
        """修改购物车"""
        # 调用序列化器校验数据
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 判断用户登陆状态
        try:
            user = request.user
        except Exception:
            user = None

        # 如果已登陆,从redis取回购物车信息
        if user and user.is_authenticated:
            # 连接数据库
            redis = get_redis_connection('cart')

            pl = redis.pipeline()
            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_200_OK)

        else:
            # 获取cookie中购物车数据
            cart = request.COOKIES.get('cart')
            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            # 添加购物信息
            cart[sku_id] = {
                "count": count,
                "selected": selected,
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)
            response.set_cookie("cart",
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRE)
            return response
Beispiel #13
0
    def put(self, request):
        """
        修改购物车数据
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 尝试对请求的用户进行验证
        try:
            user = request.user
        except Exception:
            # 验证失败,用户未登录
            user = None

        if user is not None and user.is_authenticated:
            # 用户已登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)
        else:
            # 用户未登录,在cookie中保存
            # 使用pickle序列化购物车数据,pickle操作的是bytes类型
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            cart[sku_id] = {
                'count': count,
                'selected': selected
            }
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)
            # 设置购物车的cookie
            # 需要设置有效期,否则是临时cookie
            response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #14
0
    def put(self, request):
        """修改购物车的数据"""
        # 取出数据
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')
        # 用户进行验证
        try:
            user = request.user

        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 用户已经登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # HSET key field value, 数据库操作
            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                # SADD key member [member ...]
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)
        else:
            # 用户未登录,在cookie中保存
            cart = request.COOKIES.get('cart')  # str
            if cart:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            cart[sku_id] = {'count': count, 'selected': selected}
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data)

            # 设置购物车的cookie
            response.set_cookie('cart',
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #15
0
    def post(self, request):
        """
        添加购物车
        """
        # 校验请求参数是否合法
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 获取请求参数
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        user = request.user
        if user.is_authenticated():  # 判断是否登录
            # 用户已登陆,下redis红保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipepline()
            # 增加购物车商品数量
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            if selected:  # 保存商品勾选状态
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 1.从cookie中获取购物车信息
            cart = request.COOKIES.get('cart')
            # 2.base64字符串->字典
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}
            # 3.新增字典中对应的商品数量
            sku = cart.get(sku_id)
            if sku:  # 原有数量+新增数量
                count += int(sku.get('count'))
                cart[sku_id] = {'count': count, 'selected': selected}
            # 4.字典->base64字符串
            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()
            # 5.通过cookies保存购物车数据(base64字符串)
            response = Response(serializer.data, status=201)
            # 参数3:cookie 有效期
            response.set_cookie('cart', cookie_cart,
                                constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #16
0
    def put(self, request):
        """
        修改购物车数据
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        goods_id = serializer.data.get('goods_id')
        count = serializer.data.get('count')

        # 尝试对请求的用户进行验证
        user = request.user
        redis_conn = get_redis_connection('cart')
        redis_conn.hset('cart_%s' % user.id, goods_id, count)

        datas = {  # 返回购物车总条数
            'total_count': get_cart_count(request, redis_conn)
        }
        return Response(datas)
Beispiel #17
0
    def post(self, request):
        '''
        添加购物车:
        1.获取前端提交数据,商品id:sku_id,商品数量:count,是否选中默认为true:selelcted
        2.通过序列化器校验数据
        3.视图获取校验后的数据,判断如果登陆用户保存数据到redis,未登陆保存到cookie中
        3.1登陆用户判断redis中是否有该商品,没有则添加,有则数量累加
        3.2未登陆用户接收前端请求中的cookie,没有则添加,有则解码转字典,累加数量,转字符串编码set_cookie
        :param request:
        :return:
        '''
        data = request.data
        serializer = CartSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.data['sku_id']
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')
        try:
            user = request.user
        except Exception:
            user = None
        if user != None and user.is_authenticated:
            '''redis操作'''
            redis_conn = get_redis_connection('cart')
            redis_conn.hset('cart_%s' % user.id, sku_id, count)  #hash方式写入redis
            if selected:
                redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
            return Response(serializer.data)
        else:
            '''cookie操作'''

            cart_str = request.COOKIES.get('cart')
            if cart_str is not None:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}
            if sku_id in cart_dict:
                origin_count = cart_dict[sku_id]['count']
                count += origin_count
            cart_dict[sku_id] = {'count': count, 'selected': selected}
            response = Response(serializer.data)
            cookie_cart = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('cart', cookie_cart)
            return response
Beispiel #18
0
    def post(self, request):
        data = request.data
        serializer = CartSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            redis_conn.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
            return Response(serializer.data)
        else:
            cookie_str = request.COOKIES.get('cart')
            print(type(cookie_str))
            if cookie_str is not None:

                cookie_cart = pickle.loads(
                    base64.b64decode(cookie_str.encode()))

            else:
                cookie_cart = {}
            if sku_id in cookie_cart:
                original_count = cookie_cart[sku_id]['count']
                count += original_count
            cookie_cart[sku_id] = {
                'count': count,
                'selected': selected,
            }
            # 字符串编码成二进制
            bytes_dumps = pickle.dumps(cookie_cart)
            # 编码成b64
            bytes_str = base64.b64encode(bytes_dumps)
            # 解码成字符串
            cookie_save_str = bytes_str.decode()
            response = Response(serializer.data)
            response.set_cookie('cart', cookie_save_str)
            return response
Beispiel #19
0
    def post(self, request):
        """
        添加购物车
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        goods_id = serializer.data.get('goods_id')
        count = serializer.data.get('count')

        # 尝试对请求的用户进行验证
        user = request.user
        # 用户已登录,在redis中保存
        redis_conn = get_redis_connection('cart')  # type: StrictRedis
        # 记录购物车商品数量
        redis_conn.hincrby('cart_%s' % user.id, goods_id, count)

        datas = {  # 返回购物车总条数
            'total_count': get_cart_count(request, redis_conn)
        }
        return Response(datas)
Beispiel #20
0
    def put(self, request):
        """修改购物车数据"""
        # 校验参数
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取校验后的参数
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        user = request.user
        if user.is_authenticated():
            # 用户已登陆,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 修改商品数量
            pl.hset('cart_%s' % user.id, sku_id, count)
            # 修改商品的勾选状态
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            return Response(serializer.data)

        else:
            # 未登录,从coolie中获取购物车信息
            cart = request.COOKIES.get('cart')
            # base64字符串->字典
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}
            # 修改字典中对应商品数量和选中状态
            cart[sku_id] = {'count': count, 'selected': selected}
            # 字典->base64字符串
            cookie_cart = base64.b64encode(pickle.dumps().decode())
            # 通过cookie保存购物车数据(bas64字符串)
            response = Response(serializer.data)
            response.set_cookie('cart', cookie_cart,
                                constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #21
0
    def put(self, request):
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        sku_id = serializer.data.get('sku_id')
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')

        try:
            user = request.user
        except Exception:
            user = None
        # 如果用户登陆 则更新redis数据 覆盖
        if user is not None and user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            redis_conn.hset('cart_%s' % user.id, sku_id, count)
            # 改变选中状态
            if selected:
                redis_conn.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                redis_conn.srem('cart_selected_%s' % user.id, sku_id)
            return Response(serializer.data)

        # 没有登陆
        else:
            cart = request.COOKIES.get('cart')
            # 解密
            if cart is not None:
                cookie_cart = pickle.loads(base64.b64decode(cart))
            else:
                cookie_cart = {}
            # 便利数据并更新
            if sku_id in cookie_cart:
                cookie_cart[sku_id] = {'count': count, 'selected': selected}
            # 加密
            cookie = base64.b64encode(pickle.dumps(cookie_cart)).decode()
            # 设置cookie
            response = Response(serializer.data)
            response.set_cookie('cart', cookie, 3600)

            return response
Beispiel #22
0
    def put(self, request):
        """修改购物车数据"""
        # 校验参数
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取校验后的残暑
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        select = serializer.validated_data.get('select')

        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 修改商品数量
            pl.hset('cart_%s' % user.id, sku_id, count)
            # 修改商品的勾选状态
            if select:
                pl.sadd('cart_select_%s' % user.id, sku_id)
            else:
                pl.srem('cart_select_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)
        return Response(status=301)
Beispiel #23
0
    def post(self, request):
        """
        添加购物车
        # sku_id, count, selected
        如果用户登录: 保存到redis; 格式: hash->('user_id':{'sku_id':'count', 'sku_id':'count'}); set -> cart_selected_user_id : (sku_id, sku_id...)
        如果用户未登录: 保存到 cookies; 格式: cookies已经唯一标记一个用户了, 所以保存格式弄成json('字典'类型) {'sku_id':{'count':count, 'selected':selected}}
        - 需要进行格式的转换: pickle -> base64
        """
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 异常捕获: 尝试对请求的用户进行验证(上面的perform_authentication()重写,是为了让用户正常的进入视图方法中,但是这里还是要进行登录的验证)
        # 这里可以参看用户验证的时候源码, 返回的是 request.user 实际上这里和我们理解的不一样,这里user是属性方法
        try:
            user = request.user
        except Exception:
            # 验证未通过
            user = None
        if user is not None and user.is_authenticated:  # 如果不进行这一步验证,前端可能通过请求头传递一个匿名用户对象: AnonymousUser
            # 用户已经登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 记录购物车的勾选项
            # 勾选
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
        else:
            # 用户未登录,在cookie中保存   response = Response()  response.set_cookie
            # {
            #     1001: { "count": 10, "selected": true},
            #     ...
            # }
            # 使用pickle序列化购物车数据,pickle操作的是bytes类型
            cart_str = request.COOKIES.get('cart')
            if cart_str:
                # 解析
                cart_str = cart_str.encode()  # str-bytes  ???
                cart_bytes = base64.b64decode(cart_str)
                cart_dict = pickle.loads(cart_bytes)
            else:
                cart_dict = {}
            sku = cart_dict.get(sku_id, None)
            if sku:
                # 如果已经存在,那么累加商品,并且
                cart_dict[sku_id]['count'] += count
                cart_dict[sku_id]['selected'] = selected
            else:
                # 如果商品不在购物车中
                cart_dict[sku_id] = {
                    'count': count,
                    'selected': selected
                }
            cart_cookies = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 设置cookies
            response = Response(serializer.data)
            response.set_cookie('cart', cart_cookies, max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #24
0
    def post(self, request):
        """
        购物车记录添加
        1.获取参数并进行校验(参数完整性, sku_id对应的商品是否存在,库存是否足够)
        2.保存用户的购物车记录
            2.1 登录的用户 redis
            2.2 未登录的用户 cookies
        3.返回应答,购物车记录添加成功

        """
        # 购物车记录添加
        # 1.获取参数并进行校验(参数完整性, sku_id对应的商品是否存在,库存是否足够)
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取参数
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']
        # 获取user  不管登录没有都有user参数
        try:
            user = request.user
        except Exception:
            user = None
        # 2.保存用户的购物车记录
        if user and user.is_authenticated:
            # 2.1 如果用户已登录,在redis中保护用户肚饿购物车记录
            # 获取redis链接
            redis_conn = get_redis_connection('carts')
            # 在redis中存储用户添加商品的count hash
            cart_key = 'cart_%s' % user.id
            pl = redis_conn.pipeline()
            # 如果sku_id商品在购物车已经添加过了,则是数量的累加
            # 如果没有添加过, 则是设置新的属性,值
            pl.hincrby(cart_key, sku_id, count)

            # 在redis中存储用户购物车记录勾选状态 set
            cart_selected_key = 'cart_selected_%s' % user.id

            if selected:
                # 勾选
                pl.sadd(cart_selected_key, sku_id)

            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 2.2 未登录的用户 cookies
            cookie_cart = request.COOKIES.get('cart')  # None
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                cart_dict = {}
            # 保存购物车记录
            if sku_id in cart_dict:
                # 商品在购物车记录里,则增加数量
                count += cart_dict[sku_id]['count']
            cart_dict[sku_id] = {'count': count, 'selected': selected}
            # 3.返回应答,购物车记录添加成功
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)
            # 设置购物车cookie数据
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('cart',
                                cart_data,
                                max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #25
0
    def put(self, request):
        """
        用户的购物车记录更新:
        1. 获取参数并进行校验(参数完整性,sku_id对应的商品是否存在,商品库存是否足够)
        2. 获取user并处理
        3. 更新用户的购物车记录
            3.1 如果用户已登录,更新redis中对应购物车记录
            3.2 如果用户未登录,更新cookie中对应购物车记录
        4. 返回应答,购物车记录更新成功
        """
        # 1. 获取参数并进行校验(参数完整性,sku_id对应的商品是否存在,商品库存是否足够)
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 获取参数
        sku_id = serializer.validated_data['sku_id']
        count = serializer.validated_data['count']
        selected = serializer.validated_data['selected']

        # 2. 获取user并处理
        try:
            user = request.user
        except Exception:
            user = None
        # 3. 更新用户的购物车记录
        if user and user.is_authenticated:
            # 3.1 如果用户已登录,更新redis中对应购物车记录
            connection = get_redis_connection('carts')
            # 在redis中更新对应sku_id商品的购物车count hash
            cart_key = 'cart_%s' % user.id

            pl = connection.pipeline()

            # hset(key, field, value): 将redis中hash的属性field设置值为value
            pl.hset(cart_key, sku_id, count)
            # 在redis中更新sku_id商品的勾选状态 set
            cart_selected_key = 'cart_selected_%s' % user.id
            if selected:
                # 勾选
                # sadd(key, *members): 将set集合添加元素,不需要关注元素是否重复
                pl.sadd(cart_selected_key, sku_id)
            else:
                # 取消勾选
                # srem(key, *members): 从set集合移除元素,有则移除,无则忽略
                pl.srem(cart_selected_key, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            response = Response(serializer.data)
            # 3.2 如果用户未登录,更新cookie中对应购物车记录
            cookie_cart = request.COOKIES.get('cart')  # None

            if cookie_cart is None:
                return response

            # 解析cookie中的购物车数据
            cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            if not cart_dict:
                return response

            # 更新用户购物车中sku_id商品的数量和勾选状态
            cart_dict[sku_id] = {'count': count, 'selected': selected}

            # 4. 返回应答,购物车记录更新成功
            # 处理
            cookie_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 设置购物车cookie
            response.set_cookie('cart',
                                cookie_data,
                                expires=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #26
0
    def post(self, request):
        """
        添加购物车
        1. 校验参数(sku_id,count,selected)
        2. 判断用户是否登陆
        3. 根据用户是否登陆将购物车分别进行保存
        """

        # 使用序列化器校验参数
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 获取校验之后的参数
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 链接redis数据库
        redis_conn = get_redis_connection("cart")

        # 获取登陆用户
        try:
            user = request.user
        except Exception:
            user = None

        if user and user.is_authenticated:
            # 用户登陆状态
            # 创建key
            cart_key = "cart_%s" % user.id

            # 保存购物车中商品以及数量
            redis_conn.hincrby(cart_key, sku_id, count)

            # 创建key
            cart_selected_key = "cart_selected_%s" % user.id
            if selected:
                redis_conn.sadd(cart_selected_key, sku_id)

            # 返回应答,保存购物车记录成功
            return Response(serializer.data)

        else:
            # 用户未登陆
            # 获取客户端发送的cookie信息
            cookie_cart = request.COOKIES.get('cart')

            if cookie_cart:
                # 对cookie进行解析
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                count += cart_dict['sku_id']['count']

            cart_dict[sku_id] = {'count': count, 'selected': selected}
            # 转换成字符串
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 构建响应对象
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            # 设置cookie
            response.set_cookie('cart',
                                cart_data,
                                max_age=constants.CART_COOKIE_EXPIRES)

            return response
Beispiel #27
0
    def put(self, request):
        """修改购物车数据"""
        # 使用序列化器校验参数
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 获取校验之后的参数
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data.get('selected')

        # 链接redis数据库
        redis_conn = get_redis_connection("cart")

        # 获取登陆用户
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            # 登陆用户
            cart_key = "cart_%s" % user.id
            redis_conn.hset(cart_key, sku_id, count)

            cart_selected_key = "cart_selected_%s" % user.id
            if selected:
                redis_conn.sadd(cart_selected_key, sku_id)
            else:
                redis_conn.srem(cart_selected_key, sku_id)

            # 返回应答
            return Response(serializer.data)
        else:
            # 未登陆用户
            response = Response(serializer.data)
            # 获取客户端发送的cookie信息
            cookie_cart = request.COOKIES.get('cart')

            if not cookie_cart:
                return response

            # 解析cookie
            cart_dict = pickle.loads(base64.b64decode(cookie_cart))

            if not cart_dict:
                return response

            cart_dict[sku_id] = {'count': count, 'selected': selected}
            # 转换成字符串
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            # 构建响应对象
            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            # 设置cookie
            response.set_cookie('cart',
                                cart_data,
                                max_age=constants.CART_COOKIE_EXPIRES)

            return response
Beispiel #28
0
    def post(self, request):
        # 1.接收数据对数据进行校验
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 2.获取sku_id  count   selected
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.data.get('count')
        selected = serializer.data.get('selected')

        # 3.获取用户,根据用户信息,判断登陆状态
        try:
            user = request.user
        except Exception:
            user = None
        # 判断用户登陆状态   request.user.is_authenticated 认证用户为True  匿名为False
        if user is not None and user.is_authenticated:
            # 4.登录存储redis中
            # 连接redis
            redis_conn = get_redis_connection('cart')
            # 保存数据到redis中
            # user = request.user
            # redis_conn.hset("cart_%s" % user.id, sku_id, count)
            pl = redis_conn.pipeline()
            # 记录购物车商品数量,hash
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 勾选
            pl.sadd('cart_selected_%s' % user.id, sku_id)
            # 管道执行命令
            pl.execute()
            # 返回响应
            return Response(serializer.data)

        else:
            # 5.未登录存储cookie中    读取request.COOKIES.get()
            #     先读取cookie信息,判断cookie中是否有cookie信息     str --> base64 --> pickle --> dict
            cart_str = request.COOKIES.get('cart')
            if cart_str is not None:
                # 如果有需要读取
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                # 没有不用管
                cart_dict = {}
            # 更新购物车信息     dict
            if sku_id in cart_dict:
                # 存在
                # 获取原来的个数
                orginal_count = cart_dict[sku_id]['count']
                # 累加
                count += orginal_count
            cart_dict[sku_id] = {'count': count, 'selected': selected}
            # 对明文加密
            dumps = pickle.dumps(cart_dict)

            encode = base64.b64encode(dumps)
            # 经过base64编码之后,返回的还是bytes类型, 转换为str类型
            new_cookie = encode.decode()
            response = Response(serializer.data)

            response.set_cookie('cart', new_cookie)
            # 返回响应
            return response
Beispiel #29
0
    def post(self, request):
        # 先获取到sku_id, 校验是否存在
        # sku_id = request.query_params['sku_id']
        # count = request.query_params['count']
        # selected = request.query_params['selected']
        #
        # try:
        #     SKU.objects.get(id=sku_id)
        # except SKU.DoesNotExist:
        #     raise

        # note--注意反序列化必须使用命名参数
        serializer = CartSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        sku_id = data['sku_id']
        count = data['count']
        selected = data['selected']

        # 判断用户是否登录
        # perform_authentication获取用户对象调用了request.user方法, 所以这里我们需要手动调用该方法
        # 尝试对请求的用户进行验证, 因为所个方法, 可能会抛出异常
        try:
            user = request.user
        except Exception:
            # 验证失败,用户未登录
            user = None
        if user is not None and user.is_authenticated:
            # 用户已登录,在redis中保存
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()
            # 记录购物车商品数量
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 记录购物车的勾选项
            # 勾选
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 用户未登录保存在cookie
            cart = request.COOKIES.get('cart')
            if cart is not None:
                cart = pickle.loads(base64.b64decode(cart.encode()))
            else:
                cart = {}

            sku = cart.get(sku_id)
            if sku:
                count += int(sku.get('count'))

            cart[sku_id] = {'count': count, 'selected': selected}

            cookie_cart = base64.b64encode(pickle.dumps(cart)).decode()

            response = Response(serializer.data,
                                status=status.HTTP_201_CREATED)

            # 设置购物车的cookie
            # 需要设置有效期,否则是临时cookie
            response.set_cookie('cart',
                                cookie_cart,
                                max_age=constants.CART_COOKIE_EXPIRES)
            return response
Beispiel #30
0
    def put(self, request):
        '''
        更新购物车信息
        1.接收前端数据,sku_id,count,selected
        2.校验参数,和添加购物车相同
        3.视图获取校验后的参数
        4.判断是否是登录用户
        5.登录用户操作redis
            5.1.获取reids连接
            5.2.获取redis中记录信息,并转换为字典
            5.3.将数据count累加、selected写入字典
            5.4.将字典数据写入redis
        6.非登录用户操作cookie
            6.1.获取前端cookie数据,判断cart是否存在
            6.2.解码并可视化数据
            6.3.将数据count累加,selected写入字典
        7.返回数据
        :param request:
        :return:
        '''
        data = request.data
        serializer = CartSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        sku_id = serializer.validated_data.get('sku_id')
        count = serializer.validated_data.get('count')
        selected = serializer.validated_data['selected']
        # 获取user
        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            #redis操作
            redis_conn = get_redis_connection('cart')
            pl = redis_conn.pipeline()  #统一提交redis,减少频繁操作reids
            # 记录购物车商品数量

            pl.hset('cart_%s' % user.id, sku_id, count)
            if selected:
                pl.sadd('cart_selected_%s' % user.id, sku_id)
            else:
                pl.srem('cart_selected_%s' % user.id, sku_id)
            pl.execute()
            return Response(serializer.data)

        else:
            # cookie操作
            cart_str = request.COOKIES.get('cart')
            if cart_str is not None:
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            if sku_id in cart_dict:
                cart_dict[sku_id]['count'] = count
                cart_dict[sku_id]['selected'] = selected
            #     origin_count = cart_dict[sku_id]['count']
            #     count = origin_count
            # cart_dict[sku_id] = {
            #     'count':count,
            #     'selected':selected
            # }
            response = Response(serializer.data)
            cookie_cart = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('cart', cookie_cart)
            return response