📜  在 fastapi 中创建购物车 - 任何代码示例

📅  最后修改于: 2022-03-11 14:58:48.378000             🧑  作者: Mango

代码示例1
secret_key='cart'

class Cart(object):

def __init__(self, request,db):

    self.session = request.session
    cart = self.session.get(secret_key)

    if not cart:
        # save an empty cart in the session
        cart = self.session[secret_key] = {}

    self.cart = cart

def add(self, product, quantity=1, update_quantity=False):

    product_id = str(product.id)
    if product_id not in self.cart:
        self.cart[product_id] = {'quantity': 0,
                                 'price': str(product.price)
                                 }
    if update_quantity:
        self.cart[product_id]['quantity'] = quantity
    else:
        self.cart[product_id]['quantity'] += quantity