Shopify API通过python上传本地图像

时间:2017-01-05 15:26:43

标签: python-2.7 shopify

import shopify
from base64 import b64encode
#omitted the shopify key
shopify.ShopifyResource.set_site(shop_url)


path = "product.jpg"

new_product = shopify.Product()
new_product.title = "title"
new_product.body_html = "This is a test"

image = shopify.Image()

with open(path, "rb") as f:
    filename = path.split("/")[-1:][0]
    #encoded = b64encode(f.read()) (I tried this one as well)
    encoded = f.read()
    image.attach_image(encoded, filename=filename)

new_product.images = image
new_product.save()

我测试了两种方法:

  • encoded = b64encode(f.read())
  • encoded = f.read()

在两个测试中,输出都是相同的:

产品已成功创建,但没有图像。

我还注意到image返回image(None)new_products.images也会返回image(None)

2 个答案:

答案 0 :(得分:1)

您非常接近 - new_product.images属性必须是Image个实例的列表,而不是Image个实例。另外,如果您查看attach_image()的{​​{3}},您可以看到他们为您执行base64编码。

import shopify
#omitted the shopify key
shopify.ShopifyResource.set_site(shop_url)

path = "product.jpg"

new_product = shopify.Product()
new_product.title = "title"
new_product.body_html = "This is a test"

image = shopify.Image()

with open(path, "rb") as f:
    filename = path.split("/")[-1:][0]
    encoded = f.read()
    image.attach_image(encoded, filename=filename)

new_product.images = [image] # Here's the change
new_product.save()

答案 1 :(得分:0)

self.fake(“products / 632910392 / images”,method ='POST',body = self.load_fixture('image'),headers = {'Content-type':'application / json'})

image = shopify.Image({'product_id':632910392})

image.position = 1

binary_in = base64.b64decode( “R0lGODlhbgCMAPf / APbr48VySrxTO7IgKt2qmKQdJeK8lsFjROG5p / nz7Zg3MNmnd7Q1MLNVS9GId71hSJMZIuzTu4UtKbeEeakhKMl8U8WYjfr18YQaIbAf ==”)

image.attach_image(data = binary_in,filename ='ipod-nano.png')

image.save()