Shopify REST API无法删除商品图片问题排查求助
问题排查:调用Shopify REST API删除商品图片返回200但未生效
我编写了如下Python自定义函数,通过requests库调用Shopify REST API删除商品图片:
headers = {"Accept": "application/json", "Content-Type": "application/json"} def delete_product_image(shop_url, product_id, image_id,headers): del_r = requests.delete(f'{shop_url}/products/{product_id}/images/{image_id}.json()',headers=headers) if del_r.status_code in [200, 201]: print(f'image {image_id} of product {product_id} removed') else: print(f'Error: {del_r.status_code} - {del_r.text}') time.sleep(1) delete_product_image(shop_url, product_id, image_id)执行该函数时,del_r返回200状态码,但商品图片并未被删除,请问问题出在哪里?
问题根源
- URL格式错误:请求URL末尾多了多余的
(),正确的Shopify删除商品图片接口URL应该是{shop_url}/products/{product_id}/images/{image_id}.json。错误的URL会让请求指向一个不存在的端点,但Shopify可能返回200状态码(路由容错处理),实际并未执行删除操作,这是核心问题。 - 状态码判断逻辑错误:Shopify REST API中,删除资源成功的状态码是200或204,201是创建资源时的状态码,这里判断201属于无效逻辑,但不是删除失败的直接原因。
- 无限递归风险:当前代码在非200/201状态下会无限递归重试,没有终止条件,极易引发栈溢出。
修正后的代码
import requests import time headers = {"Accept": "application/json", "Content-Type": "application/json"} def delete_product_image(shop_url, product_id, image_id, headers, max_retries=3): # 修正URL,移除末尾多余的() request_url = f'{shop_url}/products/{product_id}/images/{image_id}.json' del_r = requests.delete(request_url, headers=headers) # 匹配Shopify正确的删除成功状态码 if del_r.status_code in [200, 204]: print(f'image {image_id} of product {product_id} removed') return True else: print(f'Error: {del_r.status_code} - {del_r.text}') # 有限次数重试,避免无限递归 if max_retries > 0: time.sleep(1) return delete_product_image(shop_url, product_id, image_id, headers, max_retries - 1) else: print(f'删除失败,已重试{3}次') return False
内容的提问来源于stack exchange,提问作者LucSpan
相关产品推荐
相关产品推荐

