Home > Software engineering >  Make FLASK API run for each part of a JSON
Make FLASK API run for each part of a JSON

Time:01-18

I have this FLASK API that receives a JSON through a POST and runs a local exe with parameters from the JSON, now here is how the json looks like :

{
    "albumID": "4321",
    "folderID": "test",
    "subfolderID": "test1",
    "pictures": [
        {
            "pic": "jpg.;1",
            "picname": "flower",
            "typeID": 2
        },
        {
            "pic": "png.;2",
            "picname": "mountain",
            "typeID": 1
        }
    ]
}

My code:

for x in range(len(payload["components"])):
    data = {
        "picID": payload["picID"],
        "subfolderID": payload["subfolderID"],
        "pictures": payload["pictures"][x],
    }

Now my Python code would run a line like this with the received values :

os.system(('cmd /c pic_sizer.exe -s ' subfolderID ' -f "' folderID '" -p ' picID ' -pn' picname ' -t' typeID))

I would like the API to run for each instance of pictures, you see in the JSON above I have two but it can have 2 it can have 8,9 etc, so now my question is how would I do this ? Thank you.

CodePudding user response:

As Azhar Khan mentioned, you can iterate over the pictures list, extract the necessary information and run the command:

for picture_info in data['pictures']:
    picID = picture_info['pic'].split(';')[1]
    os.system(f"cmd /c pic_sizer.exe -s {data['subfolderID']} -f '{data['folderID']}' -p {picID} -pn {picture_info['picname']} -t {picture_info['typeID']}")

I wasn't sure where the picID value was coming from, since there is no picID key in the JSON, so I made an assumption that it is in each picture object, within the pic field right after the ;.

  • Related