javascriptflasksessionjinja2cart

How to add and remove sessions from jinja template? or eventually how to make a cart functionality?


Is there any way to manage (add and remove) sessions from Jinja template without interacting with any kind of API or page reload?

Im making a cart function for a store website, and I wanted to store items as:

session['cart'][str(item.id)] = [item.name, item.item_type, item.id]

which is a dictionary inside session storing list of three values and I can access it using

{{ session.cart[item.id|string] }}

It was easy in the backend but I wonder if I can do it inside Jinja template, like this:

{% set session.cart[item.id|string] = [item.name, item.item_type, item.id] %}

is it possible?

not to mention that I want to use it with javascript event listener

If not possible, let me know what is the best way to add and remove from sessions and update the cart length in navbar without any reload nor refresh.

My initial algorithm was to make a rest API route that would add and remove from the cart session as mentioned above, but I couldn't make it work, and here is the cart route code:

@app.route('/cart/api')
def cart_api():
    data = flask.request.args
    data = [data['nm'], data['typ'], data['id']]
    if flask.request.args.get('act') == '1':
        flask.session['cart'][data[2]] = data
        return f"{data[0]} added to cart successfuly."
    
    else:
        flask.session['cart'].remove(data[2])
        return f"{data[0]} was not found in session.", 404

when I use the API only and send the following request, it will return a 200 status code and say that item added to cart as it should, but there is no update on the main page where I have my website

HTTP://mydomain/cart/api?nm=abc&typ=alphabet&id=6&act=1

the response:
abc added to cart successfully.

Solution

  • There is no way to assign a new value to the session within the template. The difference is that Jinja runs on the server side and JavaScript runs on the client side.

    You can use JavaScript (AJAX) to call your endpoint and update your cart without reloading the page.

    The Fetch API gives you the option to do this.

    -Detlef (in coment section)