skip to Main Content
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()

I tested both methods:

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

In both tests, the output was the same:

The product was successfully created, however, with no image.

I also noticed that the image returns image(None) and new_products.images returns image(None) as well.

2

Answers


  1. You were so close- the new_product.images attribute must be a list of Image instances, not an Image instance. Also, if you look at the source of attach_image(), you can see they do the base64 encoding for you.

    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()
    
    Login or Signup to reply.
  2. 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()

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search