How to change shopping cart logic with python style

There was a blog post written about the business logic of shopping cart, which used cookie s and redis to store the data of shopping cart of the unregistered and logged-in users. Although the business logic has been well completed, the redundancy of modern codes is very serious, and they are not Python-specific enough. Today let me use python-specific, high-power grid. Let's rewrite the shopping cart logic.

Looking back at the previous code, we will find that shopping cart data will often be taken out, and then data will be modified. Can we encapsulate read and write operations? Secondly, cookie s and redis store data in different formats. Can we consider storing the two as a format? Thirdly, consider data passing through. Network transmission, can we store as little data as possible?

In redis, we used to store the quantity of goods and the checking status of goods as hash and set respectively, while in cookie s, we saved a large dictionary, and then converted the large dictionary into a string. In redis, we can also use the same storage method. Compared with nested dictionaries in dictionaries, there are only two groups in our small dictionary. Data, we can use a list to directly store the number of goods and check status, remember the corresponding subscripts, so that we do not need to spend space to store redundant key values. To determine the storage mode, we need to think about how to encapsulate it. python is an object-oriented language and has the characteristics of multi-inheritance, so we can encapsulate the read-write operation by expanding the class, and adopt the multi-inheritance method in the corresponding view class to introduce the read-write method.

class CartMixin(object):
    """Shopping cart extension class"""
    str_to_dict_class = (str.encode, base64.b64decode, pickle.loads)
    dict_to_dict_class = (pickle.dumps, base64.b64encode, bytes.decode)

    def conversion_and_encryption(self, key):
     # Method of converting data into required format if isinstance(key, dict): for func in self.dict_to_dict_class: key = func(key) else: for func in self.str_to_dict_class: key = func(key) return key def get_cart_dict(self, request):
     # The Method of Obtaining Shopping Cart try: user = request.user except Exception: user = None if user and user.is_authenticated: return self.get_cart_from_redis(request) else: return self.get_cart_from_cookie(request) def write_cart_dict(self, cart_dict, request, response):
     # Method of Writing Shopping Cart Data try: user = request.user except Exception: user = None if user and user.is_authenticated: self.write_cart_to_redis(cart_dict, user) return response else: response = self.write_cart_to_cookie(cart_dict, response) return response def get_cart_from_redis(self,request):
     # Getting a shopping cart from redis redis_conn = get_redis_connection('cart') redis_cart = redis_conn.get('cart:%s'%request.user.id) if not redis_cart: return {} # redis_cart = pickle.loads(base64.b64decode(redis_cart)) cart_dict = self.conversion_and_encryption(redis_cart.decode()) return cart_dict def get_cart_from_cookie(self,request):
     # The Method of Obtaining Shopping Cart from cookie cart_dict = request.COOKIES.get('cart') if cart_dict: # cart_dict = pickle.loads(base64.b64decode(cart_dict.encode())) cart_dict = self.conversion_and_encryption(cart_dict) else: cart_dict = {} return cart_dict def write_cart_to_redis(self, cart_dict, user):
     # Method of Writing Shopping Cart Data to redis redis_conn = get_redis_connection('cart') # cart_dict = base64.b64encode(pickle.dumps(cart_dict)).decode() cart_dict = self.conversion_and_encryption(cart_dict) redis_conn.set('cart:%s'%user.id, cart_dict) def write_cart_to_cookie(self, cart_dict, response):
     # Method of writing shopping cart data to cookie # cart_cookie = base64.b64encode(pickle.dumps(cart_dict)).decode() cart_cookie = self.conversion_and_encryption(cart_dict) response.set_cookie('cart', cart_cookie, max_age=constants.CART_COOKIE_EXPIRES) return response

In order to ensure the reliability and security of data, we will store some data processing. Considering that there are many places where data processing may be used, we will encapsulate the operation of data processing into corresponding methods. At the same time, we may also process data in different ways, so we will process data. The method is put into a list and stored in the class attribute method. When you need to change, you just need to change the corresponding class attribute. In this way, we complete the encapsulation of the read-write operation, and call the corresponding method where the read-write operation is needed. This reduces code redundancy.

In the corresponding business logic, we should only consider the needs of business, without considering the user's login status. At the same time, the reading and writing of shopping cart data is irrelevant to our business logic. The judgement of login status has been encapsulated in extended classes. For reading and writing, we can do not need to operate in the business logic of the view. In the drf framework, an initialization operation will be performed before the request comes in, and the final processing will be done before the response returns to the front end. We can In view class, rewrite these two methods, inherit the operation of parent class, and add the read-write operation we need, so as to realize the separation of read-write operation and business logic.

 

class CartView(CartMixin, APIView):
    '''Shopping Cart'''
    permission_classes = [IsAuthenticated]

    def perform_authentication(self, request):
        """
        //Rewrite the user authentication method of the parent class and check the JWT before entering the view
        """
        pass

    def initial(self, request, *args, **kwargs):
        super().initial(request, *args, **kwargs)
        self.cart_dict = self.get_cart_dict(request)

    def finalize_response(self, request, response, *args, **kwargs):
        response = super().finalize_response(request, response, *args, **kwargs)
        self.response = self.write_cart_dict(self.cart_dict, request, response)
        return self.response

 

At this point, the code rewriting is complete.

 

 

New bloggers exercise themselves by writing blogs. If they want to communicate with each other, they can improve my qq595395786.

Keywords: Python Redis Attribute network

Added by djopie on Fri, 16 Aug 2019 12:50:53 +0300