You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Shopify Python API为单个产品上传多张图片?

解决Shopify Python API多图上传问题

看了你的代码,问题出在图片内容读取的部分——你只读取了第一张图片的内容,却把它同时赋值给了两个Image对象,这就导致两张图其实是同一张,看起来就像只上传了一张。另外,还有几个小细节可以优化,确保多图上传顺利完成。

你的代码里的核心问题

你打开了path(audi.jpg)并读取了它的内容到encoded变量,但没有读取path2(audi2.jpg)的内容,直接把同一个encoded传给了image2.attach_image(),这会让两张图片都是audi.jpg的内容。

修正后的完整代码

import shopify

API_KEY = 'dsfsdsdsdsdsad'
PASSWORD = 'sadsdasdasdas'
shop_url = "https://%s:%s@teststore.myshopify.com/admin" % (API_KEY, PASSWORD)
shopify.ShopifyResource.set_site(shop_url)

path = "audi.jpg"
path2 = "audi2.jpg"

new_product = shopify.Product()
new_product.title = "Audi pictures test "
new_product.body_html = "body of the page <br/><br/> test <br/> test"

# 创建产品变体
variant = shopify.Variant({'price': 1.00, 'requires_shipping': False,'sku':'000007'})
new_product.variants = [variant]

# 分别处理每张图片,读取各自的文件内容
image_list = []

# 处理第一张图
with open(path, "rb") as f:
    filename = path.split("/")[-1]
    encoded_img = f.read()
    image = shopify.Image()
    image.attach_image(encoded_img, filename=filename)
    image_list.append(image)

# 处理第二张图
with open(path2, "rb") as f:
    filename2 = path2.split("/")[-1]
    encoded_img2 = f.read()
    image2 = shopify.Image()
    image2.attach_image(encoded_img2, filename=filename2)
    image_list.append(image2)

# 将图片列表赋值给产品并保存
new_product.images = image_list
new_product.save()

额外优化建议

  • 如果要上传更多图片,可以把图片处理逻辑封装成一个函数,避免重复代码:
    def create_shopify_image(file_path):
        with open(file_path, "rb") as f:
            filename = file_path.split("/")[-1]
            encoded = f.read()
            img = shopify.Image()
            img.attach_image(encoded, filename=filename)
            return img
    
    # 调用示例
    image_list = [create_shopify_image(path), create_shopify_image(path2)]
    
  • 可以给图片设置position属性,指定它们在产品页面的显示顺序,比如image.position = 1、image2.position = 2,这样能确保图片按你想要的顺序展示。

内容的提问来源于stack exchange,提问作者ben olsen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:45:54