I want to build a shopping cart with FastAPI and Jinja as my template
So I need to save data for each anonymous user at the session.
Django and flask have a built-in session function that we can do it easily.
One of the solutions can be using the SQLAlchemy session but the SQLAlchemy session doesn't support anonymous users and we have to create tokens separately for each session. then we should save each data with the stored token.
Is there any other way similar to Django and Flask's built-in function?
First of all, we should create cart file at our cart application then we build Cart class with our desired function.
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
then we should create cart_add API:
@app.post("/add")
def cart_add(request: Request,db: Session = Depends(get_db), id: int=Form(...), quantity: int=Form(...),
update:bool=Form(...)):
cart=Cart(request,db)
product=db.query(models.Product).filter(models.Product.id == id).first()
cart.add(product=product, quantity=quantity, update_quantity=update)
return RedirectResponse(url="/cart", status_code=status.HTTP_303_SEE_OTHER)
And that's it. we saved anonymous user's shopping cart at the session by fastapi.Request.session builtin function and it will save our data in the cookies.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With