使用Shopify Python API设置产品库存数量遇阻求助
解决Shopify Python API设置库存数量的问题
问题分析
你遇到的ResourceNotFound错误核心原因有两点:
- 手动创建
InventoryItem的方式错误,Shopify在创建Variant时会自动生成对应InventoryItem,无需手动实例化。 - 设置
InventoryLevel时参数使用错误,且未正确完成库存项与仓库位置的关联。
修正后的完整代码
def CreateShopifyProduct(data): # 创建产品 product = shopify.Product() product.title = data['title'] product.body_html = data['description'] if 'category' in data: # 修正原代码拼写错误:catagory → category product.product_type = data['category'] if 'vendor' in data: product.vendor = data['vendor'] # 处理产品图片 if 'image_url' in data: image = shopify.Image() image.src = data['image_url'] product.images = [image] else: try: image = GetLocalImageFiles(data['id']) product.images = [image] except: print("No local images found") # 保存产品 if not product.save(): print("Product save error") print(product.errors.full_messages()) return # 创建变体(自动生成InventoryItem) variant = shopify.Variant() if 'ean' in data: variant.barcode = data['ean'] variant.price = data['gross_price'] variant.weight = data['weight'] variant.inventory_management = 'shopify' # 开启库存追踪 variant.product_id = product.id # 保存变体,此时Shopify自动生成对应InventoryItem if not variant.save(): print("Variant save error") print(variant.errors.full_messages()) return # 获取自动生成的InventoryItem ID inventory_item_id = variant.inventory_item.id location_id = 61527654518 # 替换为你的实际仓库ID # 关联库存项与仓库并设置库存数量 try: # 检查是否已关联,未关联则先执行connect existing_level = shopify.InventoryLevel.find(location_ids=location_id, inventory_item_ids=inventory_item_id) if not existing_level: shopify.InventoryLevel.connect(location_id=location_id, inventory_item_id=inventory_item_id) # 设置库存数量 shopify.InventoryLevel.set( location_id=location_id, inventory_item_id=inventory_item_id, available=data['inventory'] ) print("Inventory level set successfully") except Exception as e: print(f"Inventory level error: {str(e)}") # 检查最终错误 if product.errors: print("Product errors") print(product.errors.full_messages())
关键修正说明
- 移除手动创建InventoryItem的代码:当设置
variant.inventory_management = 'shopify'并保存变体后,Shopify会自动生成InventoryItem,直接通过variant.inventory_item.id获取其ID即可。 - 规范InventoryLevel调用:
InventoryLevel.set必须使用命名参数,且确保location_id和inventory_item_id为店铺内的有效ID。 - 增加关联检查:设置库存前需确认库存项与仓库已关联,未关联时调用
InventoryLevel.connect完成绑定。 - 修复拼写错误:原代码中
catagory拼写错误,改为category避免产品类型设置失败。
排查要点
- API版本验证:确保使用2021-01及以上版本的Shopify API,该版本开始稳定支持
InventoryLevel接口。 - 权限检查:确认API令牌拥有
write_inventory权限。 - 仓库ID有效性:可通过
shopify.Location.find()获取店铺所有仓库列表,确认使用的location_id有效。
内容的提问来源于stack exchange,提问作者caf9
相关产品推荐
相关产品推荐

