标签:selectall nts raise cat 设计 sele const 请求方式 response
请求方式 : PUT /cart/selection/
请求参数: JSON 或 表单
参数 | 类型 | 是否必须 | 说明 |
---|---|---|---|
selected | bool | 是 | 是否全选,true表示全选,false表示取消全选 |
返回数据:JSON
返回值 | 类型 | 是否必须 | 说明 |
---|---|---|---|
message | str | 是 | ok |
在carts/serializers.py中新建序列化器
class CartSelectAllSerializer(serializers.Serializer):
"""
购物车全选
"""
selected = serializers.BooleanField(label=‘全选‘)
在carts/views.py中新建视图
class CartSelectAllView(APIView):
"""
购物车全选
"""
def perform_authentication(self, request):
"""
重写父类的用户验证方法,不在进入视图前就检查JWT
"""
pass
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()
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
标签:selectall nts raise cat 设计 sele const 请求方式 response
原文地址:https://www.cnblogs.com/hzlnice/p/9393134.html