Getting started with day99-redis & adding, deleting and modifying shopping cart & shopping cart data structure

Getting started with day99-redis & adding, deleting and modifying shopping cart & shopping cart data structure

1. Start redis

Enter the redis decompression directory
Run redis-server.exe redis.windows.conf from the command line

2. Python link redis, enter the ConnectionPool to view and configure according to the specific configuration required

# redis connection pool
POOL = redis.ConnectionPool(host='127.0.0.1',
                            port=6379,
                            decode_responses=True)

REDIS_CONN = redis.Redis(connection_pool=POOL)

3. Basic usage of redis

3.1 .set() and .get()

3.2 .hset() and .hget()

3.3 .hmset() and .hgetall()

3.4 .scan_iter()

3.5 .exists()

3.6 .delete()

3.7 .keys()

4. Nesting of dictionaries, pay attention to the serialization of json★★★★★

5. Add, delete, modify, view shopping cart

class ShoppingCarView(APIView):
    authentication_classes = [authentication.MyAuthentication,]

    @staticmethod
    def post(request):
        my_res = BaseResponse()
        # {"course_id": 1, "price_policy_id": 1}
        try:
            """1. Determine whether the course is legal"""
            course_id = request.data.get('course_id','')
            course_obj = models.Course.objects.filter(id=course_id).first()
            if not course_obj:
                raise MyException(101,'The course is illegal or does not exist!')

            """2. Determine whether the price strategy is legal"""
            price_policy_id = request.data.get('price_policy_id','')
            all_price_policy_query_set = course_obj.price_policy.all()
            if not all_price_policy_query_set.filter(id=price_policy_id).first():
                raise MyException(102,'Price strategy is illegal')

            """3. Get the course information"""
            course_info = {
                'title': course_obj.title,
                'course_img': str(course_obj.course_img),
                'category': course_obj.category.title,
                'course_type': course_obj.get_course_type_display(),
                'brief': course_obj.brief,
                'level': course_obj.get_level_display(),
            }

            """4. Get all price strategies"""
            price_policy_dict = {}
            for price_policy_obj in all_price_policy_query_set.order_by('price'):
                price_policy_dict[price_policy_obj.id] = {
                    'valid_period': price_policy_obj.get_valid_period_display(),
                    'price': price_policy_obj.price
                }

            """5. Build a shopping cart"""
            shopping_car_key = SHOPPING_CAR.format(request.user.pk, course_id)
            course_info['price_policy_dict'] = price_policy_dict
            course_info['default_price_policy_id'] = price_policy_id

            """6. Write the built shopping cart into Redis"""
            course_info = json.dumps(course_info)
            REDIS_CONN.set(shopping_car_key, course_info)
            my_res.code = 100
            my_res.msg ='Successfully added to the shopping cart! '

        except MyException as e:
            my_res.code = e.code
            my_res.msg = e.msg
        except Exception as e:
            my_res.code = -100
            my_res.msg = str(e)

        return Response(my_res.dict)

    @staticmethod
    def get(request):
        my_res = BaseResponse()
        try:
            user_id = request.user.pk
            shopping_car_key = SHOPPING_CAR.format(user_id,'*')
            """Find all keys"""
            all_shopping_car_keys = REDIS_CONN.scan_iter(shopping_car_key)
            if not all_shopping_car_keys:
                raise MyException(201,'Shopping cart does not exist')
            shopping_car = {}
            for key in all_shopping_car_keys:
                shopping_car[key] = json.loads(
                    REDIS_CONN.get(key)
                )
            my_res.code = 200
            my_res.msg ='SUCCESS'
            my_res.data = shopping_car

        except MyException as e:
            my_res.code = e.code
            my_res.msg = e.msg

        except Exception as e:
            my_res.code = -200
            my_res.msg = str(e)

        return Response(my_res.dict)

    @staticmethod
    def put(request):
        my_res = BaseResponse()
        # {"course_id": 1, "price_policy_id": 1}
        try:
            """1. Check if the course id exists in redis"""
            course_id = request.data.get('course_id','')
            shopping_car_key = SHOPPING_CAR.format(request.user.pk, course_id)
            if not REDIS_CONN.exists(shopping_car_key):
                raise MyException(301,'This course does not exist in the shopping cart')

            """2. Determine whether the price strategy is legal"""
            price_policy_id = request.data.get('price_policy_id','')
            price_policy_query_set = models.Course.objects.filter(id=course_id).first().price_policy.all()
            if not price_policy_query_set.filter(id=price_policy_id):
                raise MyException(402,'Price strategy is illegal')

            """3. Find the user's shopping cart from Redis, and rewrite it into Redis after modification"""
            shopping_car = json.loads(REDIS_CONN.get(shopping_car_key))
            shopping_car['default_price_policy_id'] = price_policy_id
            REDIS_CONN.set(shopping_car_key, json.dumps(shopping_car, ensure_ascii=True))
            my_res.code = 400
            my_res.msg ='SUCCESS'
            my_res.data = shopping_car

        except MyException as e:
            my_res.code = e.code
            my_res.msg = e.msg
        except Exception as e:
            my_res.code = -400
            my_res.msg = str(e)
        return Response(my_res.dict)

    @staticmethod
    def delete(request):
        # Version optimization batch delete
        my_res = BaseResponse()
        try:
            """Get the course id and determine whether it is in Redis"""
            course_id = request.data.get('course_id','')
            shopping_car_key = SHOPPING_CAR.format(request.user.pk, course_id)
            if not REDIS_CONN.exists(shopping_car_key):
                raise MyException(501,'This course does not exist in the shopping cart')
            REDIS_CONN.delete(shopping_car_key)
            my_res.code = 500
            my_res.msg ='Delete successfully! '
        except MyException as e:
            my_res.code = e.code
            my_res.msg = e.msg
        except Exception as e:
            my_res.code = -500
            my_res.code = str(e)
        return Response(my_res.dict)

6. Shopping cart data structure

shopping_car = {
        # Shopping cart data structure
        "shopping_car_ {}_ {}": {
            "id": "XXX",
            "title": "XXX",
            "course_img": "XXX",
            "price_policy_dict": {
                "valid_period": "XXX",
                "price": "XXX"
            },
            "default_price_policy_id": "XXX"
        },
}
Reference: https://cloud.tencent.com/developer/article/1603129 day99-redis introduction & addition, deletion, modification, shopping cart & shopping cart data structure-Cloud + Community-Tencent Cloud