Home > Net >  Flask - Best Way to retrieve LocalStorage on submit
Flask - Best Way to retrieve LocalStorage on submit

Time:03-02

I've created an online store using Flask and am handling the management of the shopping cart using localStorage, so I have a bunch of JavaScript functions which manage the adding and deleting items from the shopping cart, updating the HTML values and innerTexts and saves the list of all items as JSON in localStorage['CART'] in the following pattern:

{
    "data": [
        {
            "id": 7,
            "name": "Item 1",
            "gross_amount": 10.99,
            "count": 1
        },
        {
            "id": 6,
            "name": "Item 2",
            "gross_amount": 8.99,
            "count": 2
        }
    ]
}

Other than that I'm working with WTForms and on submit I now would like to retrieve that object, send it to the back end on submit so I can convert them into python objects to process the order.

Is there a way similar to request.form.data with which I can retrieve the JSON object?

Side note: In case that's not possible, I would generally only need the IDs & Count because prices are then calculated querying the database again as otherwise users could manipulate prices fiddling with the localStorage data. Maybe there is an easier way to solve this and I may just not have the experience to see the forest for the trees.

Thanks for your help

CodePudding user response:

You can make a checkout form yourself and include items using a FieldList: https://wtforms.readthedocs.io/en/3.0.x/fields/#wtforms.fields.FieldList

Or you can pass data to a flask endpoint which can parse the data structure using request.args: In Flask, what is "request.args" and how is it used?

CodePudding user response:

I did something similar to the FieldList as Jeremy suggested after the request.args stuff didn't work for me (for whatever reason)

I created a hidden FormField of String Type to which I added the JSON-String via JavaScript. This way I was able to retrieve all my form data including the Shopping Cart info from sessionStorage.

In Python I then parsed the form.data to a dictionary object using json.loads()

  • Related