json 更新API中价格的循环

efzxgjgh  于 2023-02-17  发布在  其他
关注(0)|答案(1)|浏览(102)

I am importing data from a spreadsheet to a dataframe that contains product information that I need to send in a put request through an API to update prices in an e-commerce, but I have a problem I don't know how to create the loop to iterate all the dataframe correctly.
This is an example:
| Product_Id | Variations_id | Price |
| ------------ | ------------ | ------------ |
| id001 | v0101 | 100 |
| id002 | v0201 | 120 |
| id003 | v0301 | 110 |
| id003 | v0302 | 115 |
| id004 | v0401 | 120 |
| id005 | | 130 |
Approach 1:
If the product doesn’t have variations:

url = "some_api_url" + str(product_id)

body = {‘price’: int(price)}

token = token_key

payload = json.dumps(body)
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}

response = requests.request("PUT", url, headers=headers, data=payload)
print(response.text)

Approach 2:
If the product has one variation:

url = "some_api_url" + str(product_id)
body = {
    "variations": [{
    "id": str(variation_id),
    "price": int(price)
    }
   ]   
   }

token = token_key

payload = json.dumps(body)
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}

response = requests.request("PUT", url, headers=headers, data=payload)
print(response.text)

Approach 3:
If the product_id has two or more variations append the variations_id and the price in the same body:

url = "some_api_url" + str(product_id)

body =  {
    "variations": [{
                    "id": str(variations_id_1),
                    "price": int(price_1)
            },
            {
                    "id": str(variations_id_2),
                    "price": int(price_2)
            },
            {
                    "id": str(variations_id_3),
                    "price": int(price_3)
            }
         ]
    }

token = token_key

payload = json.dumps(body)
headers = {
 'Authorization': f'Bearer {token}',
 'Content-Type': 'application/json'
}

response = requests.request("PUT", url, headers=headers, data=payload)
print(response.text)

Note: if a product has more than one variation and I omit any of them, those omitted variations are eliminated, and as a result, they are products that will disappear from the e-commerce.
How can I iterate all the dataframe that each of the product_id passes its respective variations_id and price in the JSON body and if the next product_id is the same add the variations_id and price to the current body like the product_id "id003" with two variations?

deikduxw

deikduxw1#

如何迭代每个product_id在JSON主体中传递其各自variations_id和price的所有 Dataframe

  • 使用DataFrame.iterrows并构建一个大的 * body *。只要你从每一行创建一个字典,你就不会错过任何变化。首先按产品ID排序可能是个好主意。
  • 或使用DataFrame.groupby,按产品ID分组;遍历这些组,为每个组构建一个主体,然后 * put * 它。

将对象拆分为组

相关问题