Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session in FastAPI

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?

like image 324
MK Fast Avatar asked Jan 28 '26 09:01

MK Fast


1 Answers

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.

like image 154
MK Fast Avatar answered Jan 31 '26 02:01

MK Fast