Merge cart

Merge cart logical analysis

  1. Merge direction: cookie cart Redis data into the shopping cart data.
  2. Merge Data: Cart product data and check the status.
  3. Merger plan:
    1. Redis database, shopping cart data retention.
    2. If the cookie cart Redis data already exists in the database,
      the data covered cookie cart shopping cart Redis data.

    3. If the cookie cart Redis data does not exist in the database,
      the new data to the cookie cart Redis.

    4. The final status of the shopping cart check subject to the cookie cart check status.

Merge cart logic implementation

import base64
import pickle
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, response, user):
    '''
    合并购物车中cookie的数据到redis
    :return: 
    '''
    # 1.获取cookie的数据
    cookie_cart = request.COOKIES.get('carts')

    # 2.判断数据是否存在, 如过不存在, 返回
    if not cookie_cart:
        return response

    # 3.如果存在, 解密
    cart_dict = pickle.loads(base64.b64decode(cookie_cart))

    new_dict = {} # hash: user_id:{sku_id:count}
    new_add = []
    new_remove = []
    # 4.整理格式(dict add remove)
    for sku_id, dict in cart_dict.items():
        new_dict[sku_id] = dict.get('count')

        if dict['selected']:
            # true
            new_add.append(sku_id)
        else:
            # false
            new_remove.append(sku_id)

    # 5.链接redis
    redis_conn = get_redis_connection('carts')

    # 6.往hash写入(dict)
    redis_conn.hmset('carts_%s' % user.id, new_dict)

    # 7.往set中增加或者删除
    if new_add:
        redis_conn.sadd('selected_%s' % user.id, *new_add)

    if new_remove:
        redis_conn.srem('selected_%s' % user.id, *new_remove)

    # 8.删除cookie
    response.delete_cookie('carts')

    # 9.返回
    return response

Guess you like

Origin www.cnblogs.com/oklizz/p/11241129.html