def put(self, request): serializer = CartSelectAllSerializer(data=request.data) serializer.is_valid(raise_exception=True) 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') sku_id_list = redis_conn.hgetall('cart_%s' % user.id) if selected: # 将购物车中所有的商品sku_id全部加入 set redis_conn.sadd('cart_selected_%s' % user.id, *sku_id_list) else: # 反选, 执行删除操作 redis_conn.srem('cart_selected_%s' % user.id, *sku_id_list) return Response({'message': 'OK'}) else: # 用户未登录,操作 cookie cart_cookies = request.COOKIES.get('cart') if cart_cookies: # cookie 中有 购物车 数据 cart_dict = pickle.loads(base64.b16decode(cart_cookies.encode())) else: cart_dict = {} # cart_dict = { # sku_id_1: { # 'count': 10 # 'selected': True # }, # sku_id_2: { # 'count': 10 # 'selected': False # }, # } response = Response({'message': 'OK'}) for count_selected_dict in cart_dict.values(): count_selected_dict['selected'] = selected # 设置 cookies 并 返回 cart_cookies = base64.b64encode(pickle.dumps(cart_dict)).decode() response.set_cookie('cart', cart_cookies, max_age=constants.CART_COOKIE_EXPIRES) return response
def put(self, request): serializer = CartSelectAllSerializer(data=request.data) serializer.is_valid(raise_exception=True) selected = serializer.validated_data['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') cart = redis_conn.hgetall('cart_%s' % user.id) sku_id_list = cart.keys() # print(cart) # print(redis_conn.smembers('cart_selected_%s' % user.id)) # note--b'num'转化成正常的数字 # print(int(b'10')) if selected: # 全选 redis_conn.sadd('cart_selected_%s' % user.id, *sku_id_list) else: # 取消全选 redis_conn.srem('cart_selected_%s' % user.id, *sku_id_list) return Response({'message': 'OK'}) else: # cookie cart = request.COOKIES.get('cart') response = Response({'message': 'OK'}) if cart is not None: cart = pickle.loads(base64.b64decode(cart.encode())) for sku_id in cart: cart[sku_id]['selected'] = selected cookie_cart = base64.b64encode(pickle.dumps(cart)).decode() # 设置购物车的cookie # 需要设置有效期,否则是临时cookie response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES) return response
def put(self, request): serializer = CartSelectAllSerializer(data=request.data) serializer.is_valid(raise_exception=True) selected = serializer.validated_data['selected'] try: user = request.user except Exception: user = None if user is not None and user.is_authenticated: redis_conn = get_redis_connection('cart') cart = redis_conn.hgetall('cart_%s' % user.id) sku_id_list = cart.keys() if selected: # 全选 redis_conn.sadd('cart_selected_%s' % user.id, *sku_id_list) else: # 取消全选 redis_conn.srem('car_selected_%s' % user.id, *sku_id_list) return Response({'message': 'OK'}) else: cart = request.COOKIES.get('cart') response = Response({'message': 'OK'}) if cart is not None: cart = myjson.loads(cart) for sku_id in cart: cart[sku_id]['selected'] = selected cookie_cart = myjson.dumps(cart) # 设置购物车的cookie response.set_cookie('cart', cookie_cart, max_age=constants.CART_COOKIE_EXPIRES) return response
def put(self, request): # 1. 获取前端json数据 data = request.data # 2. 序列化数据,并取出三个数据(sku_id, count, selected) serializer = CartSelectAllSerializer(data) selected = serializer.data['selected'] # 3. 用户登录判断 try: user = request.user except: user = None # 3.1 用户已登录 if user is not None: # 3.1.1 链接数据库 conn = get_redis_connection('carts') # 3.1.2 Hash类型保存 sku_id_conut = conn.hgetall('cart_%s' % user.id) sku_id_list = sku_id_conut.keys() # 3.1.3 Set类型保存 if selected: conn.sadd('cart_selected_%s' % user.id, *sku_id_list) else: conn.srem('cart_selected_%s' % user.id, *sku_id_list) # 3.1.4 返回响应 return Response(serializer.data) # 3.2 用户未登录 else: response = Response(serializer.data) # 3.2.1 获取cookie,并判断。为空置为{} cart_cookie = request.COOKIES.get('cart_cookie') # 3.2.2 如果存在,cookie解码,并判断是否存在响应商品,如果存在,数量增加 if cart_cookie: # 解码 cart = pickle.loads(base64.b64decode(cart_cookie.encode())) for sku_id in cart.keys(): cart[sku_id]['selected'] = selected cart_cookie = base64.b64encode(pickle.dumps(cart)).decode() response.set_cookie('cart_cookie', cart_cookie, 60 * 60 * 24) return response
def put(self, request): """全选/取消全选""" # 使用序列化器校验参数 serializer = CartSelectAllSerializer(data=request.data) serializer.is_valid(raise_exception=True) # 获取校验之后的参数 selected = serializer.validated_data.get('selected') # 创建redis链接对象 redis_conn = get_redis_connection('cart') # 获取user对象 try: user = request.user except Exception: user = None if user is not None and user.is_authenticated: # 用户登陆状态 if selected: # 全选 cart_key = 'cart_%s' % user.id # 获取hash中所有的属性 sku_ids = redis_conn.hkeys(cart_key) cart_selected_key = "cart_selected_%s" % user.id # 向set集合中添加元素,忽略已添加的元素 redis_conn.sadd(cart_selected_key, *sku_ids) else: # 取消全选 cart_key = 'cart_%s' % user.id # 获取hash中所有的属性 sku_ids = redis_conn.hkeys(cart_key) cart_selected_key = "cart_selected_%s" % user.id # 从set集合中移除元素,存在就移除,不存在就忽略 redis_conn.srem(cart_selected_key, *sku_ids) # 返回状态 return Response({'message': 'OK'}) else: # 用户未登陆状态 cart_cookie = request.COOKIES.get('cart') if not cart_cookie: return Response({'message': 'OK'}) # 解析cookie cart_dict = pickle.loads(base64.b64decode(cart_cookie)) if not cart_dict: return Response({'message': 'OK'}) for sku_id in cart_dict.keys(): cart_dict[sku_id]['selected'] = selected # 转换为字符串 cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode() # 构建响应对象 response = Response({'message': 'OK'}) response.set_cookie('cart', cart_data, expires=constants.CART_COOKIE_EXPIRES) return response
def put(self,request): '''全选或全不选''' # selected = request.data.get('selected') # 创建序列化器,校验selected是否合法 s = CartSelectAllSerializer(data=request.data) #检验 s.is_valid(raise_exception=True) #从检验后的数据中取得selected的值 selected = s.validated_data.get('selected') # 获取用户对象 user = request.user if user.is_authenticated(): # 断是否已经登录 # cart_1 = {1: 2, 2: 2} # cart_selected_1 = {1, 2} # 用户已登录,获取操作Redis的StrictRedis对象 strict_redis = get_redis_connection('carts') # type: StrictRedis # 从redis的hash中取出用户所有的商品id: hkeys cart_1 (1, 2) sku_ids = strict_redis.hkeys('cart_%s' % user.id) if selected: #如果全选,添加商品id到redis中: sadd cart_selected_1 1 2 strict_redis.sadd('cart_selected_%s' % user.id, *sku_ids) else: # 如果全不选,则从set中删除所有商品id srem cart_selected_1 1 2 strict_redis.srem('cart_selected_%s' % user.id, *sku_ids) # 响应数据 return Response({'message':'OK'}) #未登录 else: response = Response({'message':'OK'}) # 从cookie中获取购物车信息 cart = request.COOKIES.get('cart') # 如果cookie不为空,则base64字符串 -> 字典 if cart is not None: # {1: {'count':2, 'selected':False}, 2: {'count':2, 'selected':False}} cart = pickle.loads(base64.b64decode(cart.encode())) print('cookie', cart) # 遍历字典中所有商品,修改商品的选中状态 for sku_id in cart: cart[sku_id]['selected'] = selected # 字典 --> base64字符串,已经修改 cart_cookie = base64.b64encode(pickle.dumps(cart)).decode() # 通过cookie保存购物车数据(base64字符串): response.set_cookie() response = Response({'message': 'ok'}) response.set_cookie('cart',cart_cookie, 60 * 60 * 24 * 365) # 有效期: 1年 # 响应序列化数据 return response