Answers for "creating a cart in fastapi"

0

creating a cart in fastapi

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
Posted by: Guest on September-28-2021

Browse Popular Code Answers by Language