Exemple #1
0
def creat_a_product(**kwargs):
    session = shopify.Session(shop_url, api_version, access_token)
    shopify.ShopifyResource.activate_session(session)

    variants = []
    images = []
    new_product = shopify.Product()

    for key, value in kwargs.items():
        if key == 'variants':
            for item in value:
                variant = shopify.Variant(item)
                variants.append(variant)
            value = variants
        elif key == 'images':
            for item in value:
                image = shopify.Image()
                with open(item, "rb") as f:
                    filename = item.split("/")[-1:][0]
                    encoded = f.read()
                    image.attach_image(encoded, filename=filename)
                    images.append(image)
            value = images

        setattr(new_product, key, value)
    new_product.save()
    print(new_product.id)
    print(new_product.to_dict())
Exemple #2
0
def upload(request):
    if request.method == 'POST':
        print request.POST
        with request.user.session:
            # products = shopify.Product.find()
            new_product = shopify.Product()
            new_product.title = request.POST['title'].capitalize()
            new_product.product_type = request.POST['title'].capitalize()
            new_product.body_html = request.POST['description']
            new_product.tags = request.POST['tags']
            image1 = shopify.Image()
            imagepath = request.POST['imagepath']
            with open(imagepath, "rb") as f:
                filename = imagepath.split("/")[-1:][0]
                # encoded = b64encode(f.read())
                image1.attach_image(f.read(), filename=filename)
                new_product.images = [image1]
                # new_product.images = [image1]
                success = new_product.save(
                )  #returns false if the record is invalid
                print success
                redirect_uri = "https://" + request.user.myshopify_domain + "/admin/products/"
                print redirect_uri
                return render(request, "shopify_auth/iframe_redirect.html",
                              {'redirect_uri': redirect_uri})

        # <QueryDict: {u'csrfmiddlewaretoken': [u'cL1IJD8TEP8Hteh8BJt0PR9hVirYB1NRALtUxQvjUtFy2IClheWr5mjrYE6wdW6S'], u'tags': [u'longdress, elegance, prom, style, fashion'], u'description': [u'Long dresses for elegance look and every occassion'], u'uploaded_file_url': [u'/media/d1_5BE1DTo.jpg'], u'title': [u'longdress']}>
    return render(request, 'myapp/home.html')
Exemple #3
0
def add_images_to_product(product: shopify.Product,
                          image_list: List[Image.Image],
                          make_square: bool = True,
                          resize: bool = True) -> List[shopify.Image]:
    """
    Note! We are resizing all images to squares of (2048, 2048).
    """
    logger.info(f"Adding images to Product: {product.title}")
    assert product.id is not None
    images = []
    for i, image in enumerate(image_list):
        image_format = image.format
        new_shopify_image = shopify.Image()
        new_shopify_image.product_id = product.id
        new_shopify_image.variant_ids = [
            variant.id for variant in product.variants
        ]
        if make_square:
            image = expand_to_square(image)
        if resize:
            image = image.resize((2048, 2048))
        new_shopify_image.attach_image(
            data=_image_to_bytes(image, image_format=image_format),
            filename=
            f"{product.title.replace(' ', '_').lower()}_.{image_format.lower()}",
        )
        if new_shopify_image.errors.errors:
            raise ValueError(new_shopify_image.errors.errors)
        new_shopify_image.save()
        images.append(new_shopify_image)
    return images
Exemple #4
0
def PostToShpify(request):
    shop_url = "https://%s:%[email protected]/admin" % (api, password)
    shopify.ShopifyResource.set_site(shop_url)
    url = "https://secure.chinavasion.com/api/getProductDetails.php"
    new_product = shopify.Product()
    if request.method == 'POST':
        q = request.POST['ProductName']
        dis = request.POST['dis']
        price = request.POST['price']
        mainPic = request.POST['mainPic']
        productType = request.POST['productType']

        additionalPic = request.POST.getlist('checks[]')
        print additionalPic

        new_product.title = q
        new_product.body_html = dis
        new_product.product_type = productType
        new_product.save()

        #Price
        product = shopify.Product.find(new_product.id)
        product.variants[0].price = price
        product.save()

        #Main Image
        new_image = shopify.Image()
        new_image = shopify.Image(dict(product_id=new_product.id))
        new_image.src = mainPic
        new_image.save()

        #additinola images
        #makelist1 = makelist.replace("[","").replace("u'","").replace("]","").replace(",","").replace("'","")
        for i in additionalPic:
            new_image = shopify.Image()
            new_image = shopify.Image(dict(product_id=new_product.id))
            new_image.src = i
            print i
            new_image.save()

            #print type(additionalPic)
            #print ("======>>>>>>>>>>", makelist1)
    else:
        return HttpResponseRedirect("/ChinaVasion/supp/")

    return HttpResponseRedirect("/ChinaVasion/supp/")
Exemple #5
0
  def test_create_image(self):
    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
    image.attachment = "R0lGODlhbgCMAPf/APbr48VySrxTO7IgKt2qmKQdJeK8lsFjROG5p/nz7Zg3MNmnd7Q1MLNVS9GId71hSJMZIuzTu4UtKbeEeakhKMl8U8WYjfr18YQaIbAf=="
    image.save()

    self.assertEqual('http://cdn.shopify.com/s/files/1/0006/9093/3842/products/ipod-nano.png?v=1389388540', image.src)
    self.assertEqual(850703190, image.id)
Exemple #6
0
 def to_shopify_object(
         self,
         existing_object: Optional[shopify.Image] = None) -> shopify.Image:
     if existing_object:
         obj = existing_object
     else:
         obj = shopify.Image()
     for field in self.__fields__:
         if self.__getattribute__(field) is not None:
             obj.__setattr__(field, self.__getattribute__(field))
     return obj
Exemple #7
0
def create_images(images):
    images = deepcopy(images)
    created_images = []
    for image in images:
        new_image = shopify.Image()
        new_image.position = image['position']
        new_image.width = image['width']
        new_image.height = image['height']
        new_image.src = image['src']
        created_images.append(new_image)
    return created_images
Exemple #8
0
def create_product():
    new_product = shopify.Product()
    new_product.title = "Burton Custom Freestyle 151"
    new_product.product_type = "Snowboard"
    new_product.body_html = "<strong>Good snowboard!</strong>"
    new_product.vendor = "Burton"
    image1 = shopify.Image()
    image1.src = logo

    new_product.images = [image1]
    new_product.save()
    success = new_product.save()
Exemple #9
0
    def create_images(self, product_id, variants):
        """variants: shopify Product Variant object
        product_id: shopify Product ID
        """
        for image_path, variant_indices in self.images.iteritems():

            # create the image
            image = shopify.Image()
            with open(image_path, 'rb') as fp:
                image.attach_image(fp.read())

            # associate it with the right variants
            image.product_id = product_id
            image.variant_ids = [variants[i].id for i in variant_indices]
            image.save()
Exemple #10
0
def setUpImage(i):
    attrs = {'position': i}
    image_new = shopify.Image(attributes=attrs)
    f = tempfile.NamedTemporaryFile()
    r = tuple([random.randint(0, 255) for x in range(3)])
    cmd = [
        'convert', '-size', '1024x768',
        'xc:rgb(%d, %d, %d)' % r, '-gravity', 'center', '-pointsize', '200',
        '-draw',
        "text 0,0 '%d'" % i,
        'png:%s' % f.name
    ]
    subprocess.check_output(cmd)
    image_new.attach_image(data=f.read(), filename='IMG_%d.png' % i)
    f.close()
    return image_new
Exemple #11
0
    def test_get_metafields_for_image(self):
        fake_extension = 'json?metafield[owner_id]=850703190&metafield[owner_resource]=product_image'
        self.fake("metafields",
                  method='GET',
                  extension=fake_extension,
                  body=self.load_fixture('image_metafields'))

        image = shopify.Image(attributes={
            'id': 850703190,
            'product_id': 632910392
        })
        metafields = image.metafields()

        self.assertEqual(1, len(metafields))
        for field in metafields:
            self.assertTrue(isinstance(field, shopify.Metafield))
        self.assertEqual(metafields[0].value, "Image Alt Tag")
Exemple #12
0
    def test_attach_image(self):
        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()
        binary_out = base64.b64decode(image.attachment)

        self.assertEqual(
            "http://cdn.shopify.com/s/files/1/0006/9093/3842/products/ipod-nano.png?v=1389388540",
            image.src)
        self.assertEqual(850703190, image.id)
        self.assertEqual(binary_in, binary_out)
    def put_variant(self, record, remote_id, product):
        variant = shopify.Variant({'id': remote_id})
        variant.product_id = product.id
        variant.price = round(
            record.with_context(pricelist=self.pricelist_id).price, 2)
        variant.sku = record.default_code or ''
        variant.barcode = record.barcode or ''
        variant.inventory_management = 'shopify'

        if record.image_1920:
            image = shopify.Image()
            image.alt = product.handle
            image.attachment = record.image_1920.decode('utf-8')
            image.product_id = product.id
            if self.ensure_response(image, 'save'):
                variant.image_id = image.id
            else:
                _logger.error(image.errors.errors)

        if record.product_template_attribute_value_ids:
            option_count = len(product.options)
            if option_count > 0:
                variant.option1 = record.product_template_attribute_value_ids.filtered(
                    lambda self: product.options[
                        0].name in self.display_name).name
                if option_count > 1:
                    variant.option2 = record.product_template_attribute_value_ids.filtered(
                        lambda self: product.options[
                            1].name in self.display_name).name
                    if option_count > 2:
                        variant.option3 = record.product_template_attribute_value_ids.filtered(
                            lambda self: product.options[
                                2].name in self.display_name).name

        if self.ensure_response(variant, 'save'):
            return True, variant
        else:
            _logger.error(variant.errors.errors)
            return False, variant
Exemple #14
0
        def find_image(filename, product_id, sanmar):
            """Check if image in self._images otherwise download and create it."""
            if isinstance(filename, str):
                hires = filename.split(".")
                hires[-2] = ''.join([hires[-2][:-1], 'z'])
                hires = ".".join(hires)
                url = "https://www.alphabroder.com/media/hires/{}".format(
                    hires) if not sanmar else filename

                if sanmar:
                    a = urlparse(filename)
                    hires = os.path.basename(a.path)

                file_location = os.path.join('images', hires)

                opener = urllib.request.build_opener()
                opener.addheaders = [(
                    'User-agent',
                    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                    '(KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36')]
                urllib.request.install_opener(opener)

                try:
                    urllib.request.urlretrieve(url, file_location)
                    image = shopify.Image({"product_id": product_id})
                except HTTPError:
                    image = None

                if image:
                    with open(file_location, 'rb') as f:
                        encoded = f.read()
                        image.attach_image(encoded, file_location)
                        save(image)
                return image
            else:
                return None
Exemple #15
0
    def add_new_product(filter_variant):
        """
        Method that adds a new Wheel Pros Tire to Shopify
        :param ds18_variant: Tire to add:
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method

        # Make the tags that we want to add
        tags_to_add = []
        # Brand
        #print(filter_variant)
        tags_to_add.append("Type_" +
                           str(filter_variant.get_prod_description()))

        # 2 cases
        # 1) Is a variant
        print(filter_variant)
        if filterTools.has_variants(filter_variant):
            product_id = filterTools.find_product_id(filter_variant)
            new_filter_product = shopify.Product.find(product_id)[0]
            print("Type of new_filter_project: ", type(new_filter_product))
            variant = shopify.Variant({
                'price':
                float(filter_variant.get_map_price()),
                'quantity':
                1,
                'sku':
                filter_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            # Get tags already put in
            tags = Tags()
            print("Type of new_filter_project: ", type(new_filter_product))
            tags.string_to_tags(new_filter_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_filter_product.tags = tags.tags_to_string()

            new_filter_product.tags = tags.tags_to_string()
            new_filter_product.variants.append(variant)
            new_filter_product.save()
            if new_filter_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                new_filter_product.errors.full_messages()
            filterTools.add_product(product_id, filter_variant)
            # 2) Is not a variant
        else:
            print(filter_variant)
            new_filter_product = shopify.Product()
            # Built the tire name
            new_filter_product.title = filter_variant.get_prod_description()
            new_filter_product.vendor = 'S&B Filters'
            new_filter_product.product_type = 'Filters'
            new_filter_product.body_html = """%s
                                   """ % (
                filter_variant.get_prod_description())
            variant = shopify.Variant({
                'price':
                float(filter_variant.get_map_price()),
                'quantity':
                1,
                'sku':
                filter_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            new_filter_product.variants = [variant]

            new_filter_product.tags = """S&B Filters,
                       Filters"""

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_filter_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_filter_product.tags = tags.tags_to_string()

            url_for_image = filter_variant.get_image_url().split("|")[0]
            print("The image: ", url_for_image)

            # if not ShopifyToolsFilter.url_is_alive(url_for_image):
            #    url_for_image = "https://sandbfilters.s3.us-east-2.amazonaws.com/" + filter_variant.get_part_num() + ".png"

            image = shopify.Image()
            image.src = url_for_image
            new_filter_product.images = [image]

            filterTools.add_product(new_filter_product.id, filter_variant)
            new_filter_product.save()  # returns false if the record is invalid
            if new_filter_product.errors:
                print("Hello")
                # something went wrong, see new_product.errors.full_messages() for example
                new_filter_product.errors.full_messages()
Exemple #16
0
    def add_new_tire(connection, tire_variant):
        """
        Method that adds a new Wheel Pros Tire to Shopify
        :param tire_variant: Tire to add:
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method

        # Make the tags that we want to add
        tags_to_add = []
        # Ply
        if tire_variant.get_ply() != "0":
            tags_to_add.append("Ply_" + tire_variant.get_ply())
        # Speed Rating
        # tags_to_add.append("Speed Rating_"+tire_variant.get_speed_rating())
        # Rim Diameter
        tags_to_add.append("Rim Diameter_" + tire_variant.get_rim_diameter() +
                           "\"")
        # Tire Diameter
        # tags_to_add.append("Tire Diameter_"+tire_variant.get_tire_diameter())
        # Full Model Name
        # tags_to_add.append("Model_"+tire_variant.get_full_model_name())
        # Construction Type
        tags_to_add.append("Construction Type_" +
                           tire_variant.get_construction_type())
        # Terrain
        tags_to_add.append("Terrain_" + tire_variant.get_terrain())

        # Need to find out the correct price
        if float(tire_variant.get_map_price()) == 0:
            price_for_tire = tire_variant.get_mrsp_price()
        else:
            price_for_tire = tire_variant.get_map_price()

        #Need to take out certain parts and change option1
        option1 = tire_variant.get_tire_size_description()
        option1 = option1.replace("R", "X")
        option1 = option1.replace("LT", "")
        option1 = option1.replace("-", "X")

        # 2 cases
        # 1) Is a variant
        if tireTools.has_variants(tire_variant):
            product_id = tireTools.find_product_id(tire_variant)
            new_tire_product = shopify.Product.find(product_id)
            variant = shopify.Variant({
                'price':
                float(price_for_tire),
                'option1':
                option1,
                'quantity':
                1,
                'sku':
                tire_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'deny',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                tire_variant.get_curr_stock(),
                'taxable':
                False,
                'weight':
                float(tire_variant.get_weight()),
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_tire_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_tire_product.tags = tags.tags_to_string()
            new_tire_product.variants.append(variant)
            new_tire_product.save()
            tireTools.add_tire(product_id, tire_variant)
            # 2) Is not a variant
        else:
            new_tire_product = shopify.Product()
            new_tire_product.options = [{'name': 'Tire Size'}]
            # Built the tire name
            new_tire_product.title = tire_variant.get_full_model_name()
            new_tire_product.vendor = 'Wheel Pros'
            new_tire_product.product_type = 'Tires'
            new_tire_product.body_html = """<b>%s</b>
                                   <p>%s</p>
                                   """ % (tire_variant.get_tire_description(),
                                          tire_variant.get_part_num())
            variant = shopify.Variant({
                'price':
                float(price_for_tire),
                'option1':
                option1,
                'quantity':
                1,
                'sku':
                tire_variant.get_upc(),
                'position':
                1,
                'inventory_policy':
                'deny',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                tire_variant.get_curr_stock(),
                'taxable':
                False,
                'weight':
                float(tire_variant.get_weight()),
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            new_tire_product.variants = [variant]

            new_tire_product.tags = """WheelPros,
                       Tires,
                       %s,
                       %s,
                       %s,
                       %s,""" % (tire_variant.get_full_model_name(),
                                 tire_variant.get_part_num(),
                                 tire_variant.get_tire_size(),
                                 tire_variant.get_upc())

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_tire_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            image = shopify.Image()
            file_name = tire_variant.get_picture_cd()
            image.src = file_name
            new_tire_product.images = [image]
            new_tire_product.save()

            tireTools.add_tire(new_tire_product.id, tire_variant)
            new_tire_product.save()  # returns false if the record is invalid
            if new_tire_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                new_tire_product.errors.full_messages()
            # Add to the database
        ShopifyToolsTires.add_element(
            connection, "wheel_pros_tires",
            f"('{new_tire_product.id}', '{tire_variant.get_full_model_name()}', '{tire_variant.upc}', {tire_variant.map_price}, '{option1}', '', '', {tire_variant.curr_stock}, {float(tire_variant.weight)}, '{tire_variant.get_picture_cd()}', '{tags.tags_to_string()}')"
        )
    def add_new_wheel(connection, wheel_variant):
        """
        Method that adds a new Wheel ProsWheel to Shopify
        :param wheel_variant: Wheel to add
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method

        # Make the tags that we want to add
        tags_to_add = []
        # Brand
        tags_to_add.append("Brand_" + wheel_variant.whl_manufact_nm)
        # Finish
        tags_to_add.append("Finish_" + wheel_variant.finish)
        # Bolt Pattern
        tags_to_add.append("Bolt Pattern_" + wheel_variant.bolt_pattern_metric)
        # Wheel Offset
        tags_to_add.append("Wheel Offset_" + wheel_variant.offset)
        # Wheel Size
        tags_to_add.append("Wheel Size_" + wheel_variant.size)

        # Make the bolt pattern setup
        lug_count = wheel_variant.lug_count
        dist1 = str(int(float(wheel_variant.bolt_pattern_mm_1)))
        bolt_pattern1 = lug_count + "x" + dist1
        # print(bolt_pattern1)
        dist2 = str(int(float(wheel_variant.bolt_pattern_mm_2)))
        bolt_pattern2 = ""
        if int(dist2) != 0:
            bolt_pattern2 = lug_count + "x" + dist2

        # 2 cases
        # 1) Is a variant
        if wheelTools.has_variants(wheel_variant):
            product_id = wheelTools.find_product_id(wheel_variant)
            new_wheel_product = shopify.Product.find(product_id)
            variant = shopify.Variant({'price': wheel_variant.map_price,
                                       'option1': wheel_variant.size,
                                       'option2': bolt_pattern1,
                                       'option3': wheel_variant.offset,
                                       'quantity': 1,
                                       'sku': wheel_variant.upc,
                                       'position': 1,
                                       'inventory_policy': "deny",
                                       'fulfillment_service': "manual",
                                       'inventory_management': "shopify",
                                       'inventory_quantity': wheel_variant.curr_stock,
                                       'taxable': True,
                                       'weight': float(wheel_variant.shipping_weight),
                                       'weight_unit': "g",  # g, kg
                                       'requires_shipping': True})

            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern
            variant2 = shopify.Variant({'price': wheel_variant.map_price,
                                        'option1': wheel_variant.size,
                                        'option2': bolt_pattern2,
                                        'option3': wheel_variant.offset,
                                        'quantity': 1,
                                        'sku': wheel_variant.upc,
                                        'position': 1,
                                        'inventory_policy': "deny",
                                        'fulfillment_service': "manual",
                                        'inventory_management': "shopify",
                                        'inventory_quantity': wheel_variant.curr_stock,
                                        'taxable': True,
                                        'weight': float(wheel_variant.shipping_weight),
                                        'weight_unit': "g",  # g, kg
                                        'requires_shipping': True})

            # print(type(new_wheel_product.variants))
            if bolt_pattern1 not in new_wheel_product.tags:
                new_wheel_product.tags += "," + bolt_pattern1
            if bolt_pattern2 not in new_wheel_product.tags:
                new_wheel_product.tags += "," + bolt_pattern2
            # print(new_wheel_product)
            new_wheel_product.variants.append(variant)
            if bolt_pattern2 != "":
                new_wheel_product.variants.append(variant2)
            # print("Variants: ", new_wheel_product.variants)

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_wheel_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                   tags.add_tag(t)

            new_wheel_product.tags = tags.tags_to_string()
            new_wheel_product.save()

            if new_wheel_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                raise Exception("New Wheel Product Error:\n",new_wheel_product.errors.full_messages())


            wheelTools.add_wheel(product_id, wheel_variant)

            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern

        # 2) Is not a variant
        else:
            # Update a product
            new_wheel_product = shopify.Product()
            new_wheel_product.options = [{'name': 'Tire Size'}, {'name': 'Bolt Pattern'}, {'name': 'Offset'}]
            new_wheel_product.title = wheel_variant.style_description
            new_wheel_product.vendor = "Wheel Pros"
            new_wheel_product.product_type = "Wheels"
            new_wheel_product.body_html = """<b>%s</b>
                                    <p>%s</p>
                                    """ % (wheel_variant.style_description,
                                           wheel_variant.part_number_description)
            variant = shopify.Variant({'price': wheel_variant.map_price,
                                       'option1': wheel_variant.size,
                                       'option2': bolt_pattern1,
                                       'option3': wheel_variant.offset,
                                       'quantity': 1,
                                       'sku': wheel_variant.upc,
                                       'position': 1,
                                       'inventory_policy': "deny",
                                       'fulfillment_service': "manual",
                                       'inventory_management': "shopify",
                                       'inventory_quantity': wheel_variant.curr_stock,
                                       'taxable': True,
                                       'weight': float(wheel_variant.shipping_weight),
                                       'weight_unit': "g",  # g, kg
                                       'requires_shipping': True})
            # TODO: Need to organize this code
            # Below is all for when there is a second bolt pattern
            variant2 = shopify.Variant({'price': wheel_variant.map_price,
                                       'option1': wheel_variant.size,
                                        'option2': bolt_pattern2,
                                        'option3': wheel_variant.offset,
                                       'quantity': 1,
                                       'sku': wheel_variant.upc,
                                       'position': 1,
                                       'inventory_policy': "deny",
                                       'fulfillment_service': "manual",
                                       'inventory_management': "shopify",
                                       'inventory_quantity': wheel_variant.curr_stock,
                                       'taxable': True,
                                       'weight': float(wheel_variant.shipping_weight),
                                       'weight_unit': "g",  # g, kg
                                       'requires_shipping': True})

            new_wheel_product.variants = [variant]
            if bolt_pattern2 != "":
                new_wheel_product.variants.append(variant2)

            new_wheel_product.tags = """WheelPros,Wheels"""

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_wheel_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_wheel_product.tags = tags.tags_to_string()

            image = shopify.Image()
            file_name = "%s" % wheel_variant.wheel_image
            if ShopifyTools.is_image_and_ready(file_name):
                image.src = file_name
            else:
                pass
                # Used to see when doesn't have an image
                # print(wheel_variant.upc)
                # print(wheel_variant.style_description)
                # print("-----------------")

            new_wheel_product.images = [image]
            new_wheel_product.save()

            wheelTools.add_wheel(new_wheel_product.id, wheel_variant)

            # print("PRODUCT ID: ", new_wheel_product.id)
            new_wheel_product.save()  # returns false if the record is invalid
            if new_wheel_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                raise Exception("New Wheel Product Error:\n",new_wheel_product.errors.full_messages())

        # Add to the database
        ShopifyToolsWheels.add_element(connection, "wheel_pros_wheels", f"('{new_wheel_product.id}', '{wheel_variant.style_description}', '{str(wheel_variant.upc)}', {wheel_variant.map_price}, '{wheel_variant.size}', '{bolt_pattern1}', '{wheel_variant.offset}', {wheel_variant.curr_stock}, {float(wheel_variant.shipping_weight)}, '{wheel_variant.wheel_image}', '{tags.tags_to_string()}')")
def convert_images_for_product(product, path=".", quiet=False):
    """Given a product object or id number, convert all PNGs into JPGs."""
    # A product object was given
    try:
        product_id = product.id
    # A product ID was given
    except AttributeError:
        product_id = product
        product = shopify.Product(shopify.Product.get(product_id))
    # we need a shallow copy to iterate over below (so when we edit
    # product.images we're not also editing this list while in the loop.)
    images = [i for i in product.images]

    if not os.path.isdir(path):
        os.mkdir(path)
    path_product = os.path.join(path, str(product_id))
    if not os.path.isdir(path_product):
        os.mkdir(path_product)
    for image in images:
        if not quiet:
            sys.stderr.write('%s: ' % image.src)
        if not is_png(image.src):
            if not quiet:
                sys.stderr.write('not a PNG, skipping.\n')
            continue
        if not quiet:
            sys.stderr.write('converting...\n')
        r = requests.get(image.src)
        if not r.status_code == 200:
            raise Exception('Error getting %s' % image.src)
        filename_png = os.path.basename(r.links['canonical']['url'])
        filename_jpg = os.path.splitext(filename_png)[0] + '.jpg'
        path_png = os.path.join(path_product, filename_png)
        path_jpg = os.path.join(path_product, filename_jpg)
        path_json = os.path.join(path_product, str(image.id) + '.json')

        # stash the original content, just for safety
        with open(path_json, 'w') as f:
            if not quiet:
                sys.stderr.write('    saving JSON\n')
            f.write(image.to_json())
        with open(path_png, 'w') as f:
            if not quiet:
                sys.stderr.write('    saving PNG\n')
            f.write(r.content)

        # create new image file
        cmd = ['convert', path_png, '-quality', '90%', path_jpg]
        if not quiet:
            sys.stderr.write('    executing: %s ... ' % ' '.join(cmd))
        output = subprocess.check_output(cmd)
        if not quiet:
            sys.stderr.write('%s\n' % output)

        # read in the new image data and attach to image object

        with open(path_jpg) as f:
            jpg_data = f.read()
        if jpg_data[0:2] != '\xff\xd8':
            raise Exception('JPEG prefix not found when loading %s' % path_jpg)

        # Careful, now.  If I do this, the image will have the right content,
        # but the content-type delivered by Shopify will still be image/png.
        # The safer way looks to be to create a new image object and add that
        # to the product's list of images, keeping the position value the same.
        #
        # image.attach_image(data=jpg_data, filename=os.path.basename(path_jpg))
        # image.save()

        # So, safely add a new image, and remove the old one.
        # We use the original attributes and then remove what we don't want
        # rather than explicitly adding items so that we don't inadvertantly
        # miss anything (say, variant_ids).
        attrs = {}
        attrs.update(image.attributes)
        del attrs['id']
        del attrs['src']
        image_new = shopify.Image(attributes=attrs)
        image_new.attach_image(data=jpg_data,
                               filename=os.path.basename(path_jpg))
        # TODO: reading image position from the object's attribute is not
        # reliable; I just saw a case with four images where the positions were
        # 1,2,4,4.  Maybe instead just redo this whole mess to loop over index
        # values instead.
        pos = attrs['position'] - 1
        if not quiet:
            sys.stderr.write('    replacing image object %d\n' %
                             product.images[pos].id)
        del product.images[pos]
        product.images.insert(pos, image_new)

    # Apparently save() is what actually sends the updated data to the server.
    product.save()
    def add_new_product(ds18_variant):
        """
        Method that adds a new Wheel Pros Tire to Shopify
        :param ds18_variant: Tire to add:
        :return: Returns nothing
        """
        # TODO: Need to find a way to stream line this
        # TODO: Comment out the method
        print(ds18_variant.get_model())

        # Make the tags that we want to add
        tags_to_add = []
        # Brand
        tags_to_add.append("Brand_" + ds18_variant.get_collection())

        # 2 cases
        # 1) Is a variant
        if ds18Tools.has_variants(ds18_variant):
            return
            product_id = ds18Tools.find_product_id(ds18_variant)
            new_ds18_product = shopify.Product.find(product_id)
            variant = shopify.Variant({
                'price':
                float(ds18_variant.get_msrp_price()),
                'quantity':
                1,
                'sku':
                ds18_variant.get_model(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_ds18_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_ds18_product.tags = tags.tags_to_string()

            new_ds18_product.tags = tags.tags_to_string()
            new_ds18_product.variants.append(variant)
            new_ds18_product.save()
            ds18Tools.add_product(product_id, ds18_variant)
            # 2) Is not a variant
        else:
            new_ds18_product = shopify.Product()
            # Built the tire name
            new_ds18_product.title = ds18_variant.get_name()
            new_ds18_product.vendor = 'DS 18'
            new_ds18_product.product_type = 'Sound'
            new_ds18_product.body_html = """<b>%s</b>
                                   <p>%s</p>
                                   """ % (ds18_variant.get_brand,
                                          ds18_variant.get_name())
            variant = shopify.Variant({
                'price':
                float(ds18_variant.get_msrp_price()),
                'quantity':
                1,
                'sku':
                ds18_variant.get_model(),
                'position':
                1,
                'inventory_policy':
                'continue',
                'fulfillment_service':
                'manual',
                'inventory_management':
                'shopify',
                'inventory_quantity':
                1,
                'taxable':
                False,
                'weight_unit':
                'g',
                'requires_shipping':
                True
            })
            new_ds18_product.variants = [variant]

            new_ds18_product.tags = """DS18,
                       Sound"""

            # Get tags already put in
            tags = Tags()
            tags.string_to_tags(new_ds18_product.tags)
            # Now, we can go through and add the tags we want
            for t in tags_to_add:
                if not tags.is_a_tag(t) and "nan" not in t:
                    tags.add_tag(t)

            new_ds18_product.tags = tags.tags_to_string()

            image = shopify.Image()
            image.src = "https://ds18.s3.us-east-2.amazonaws.com/" + ds18_variant.get_model(
            ).replace("-", "").replace("/", "") + ".jpg"
            new_ds18_product.images = [image]

            ds18Tools.add_product(new_ds18_product.id, ds18_variant)
            new_ds18_product.save()  # returns false if the record is invalid
            if new_ds18_product.errors:
                # something went wrong, see new_product.errors.full_messages() for example
                new_ds18_product.errors.full_messages()
Exemple #20
0
    '461824c0a06d4be0e94851deeabc3965', '9bb4f551ba4888c9199b7a9509f0e872')

shopify.ShopifyResource.set_site(shop_url)

new_product = Product()

pid = 0

new_product.vendor = "Vendor"
new_product.title = "New Product"
new_product.product_type = "Chocolate bar"
new_product.body_html = "some html"

image_filename = "http://fthumb.approvedfood.co.uk/thumbs/75/1000/296/1/src_images/hersheys_creamy_milk_chocolate_with_almonds_43g.jpg"

image1 = shopify.Image()
image1.src = image_filename
print(image1.src)
new_product.images = [image1]

success = new_product.save()  # returns false if the record is invalid
new_product.attributes['variants'][0].attributes['barcode'] = '12345'
new_product.attributes['variants'][0].attributes['compare_at_price'] = '12345'
new_product.attributes['variants'][0].attributes['grams'] = 12345
new_product.attributes['variants'][0].attributes['inventory_quantity'] = 10
new_product.attributes['variants'][0].attributes['price'] = '12345'
new_product.attributes['variants'][0].attributes['sku'] = '12345'
new_product.attributes['variants'][0].attributes['taxable'] = True
new_product.attributes['variants'][0].attributes['title'] = '12345'
new_product.attributes['variants'][0].attributes['weight'] = 1.0
new_product.attributes['variants'][0].attributes['weight_unit'] = 'kg'
Exemple #21
0
def create_shopify_products(shopify_products):
    """
    Connect to shopify store, create products based on shopify_products dict
    coming from get_tahoe_courses() function and notify admins about product
    creation
    """
    try:
        # connect to shopify store
        shopify.ShopifyResource.set_site(shopify_store_admin_api)
        store = shopify.Shop.current()
        store_admin_name = store.name
        store_admin_email = store.customer_email
        # 1 Create products in store
        # 1.1 find existing SKUs from shopify to checkproduct doesn't exist
        variants = shopify.Variant.find()
        # SKU in shopify is Course ID in OpenEDX
        skus = []
        number_created_products = 0
        created_products_list = []
        for variant in variants:
            # Fill SKUs list with all courses id that exist in shopify
            skus.append(variant.sku)
        # 1.2 loop over shopify_products and create store products
        # shopify_products contains course metadata coming from OpenEDX
        for product in shopify_products:
            # 1.3 Check if the course already exist in store
            # Remember product_sku = result["course_id"]
            if not product["product_sku"] in skus:
                # 1.4 create products in store
                new_product = shopify.Product()
                new_image = shopify.Image()
                new_product.title = product["product_title"]
                new_product.body_html = product["product_description"]
                new_product.published = "false"
                new_product.published_at = ""
                # tag is site full URL
                new_product.tags = product["product_tag"]
                new_variant = shopify.Variant(
                    {
                        "sku": product["product_sku"],
                        "requires_shipping": False,
                        "inventory_policy": "deny",
                    }
                )
                new_product.variants = [new_variant]
                product_saved = new_product.save()
                if product_saved:
                    logging.info(
                        "{}: {} created successfully".format(
                            product["product_title"], product["product_sku"]
                        )
                    )
                else:
                    logging.error(
                        "unexpected error happened for {}: {} creation".format(
                            product["product_title"], product["product_sku"]
                        )
                    )
                new_image.src = product["product_image"]
                new_product.images = new_image
                new_image.product_id = new_product.id
                image_saved = new_image.save()
                if not image_saved and not product["product_image"]:
                    logging.error("{}: {} image didn't get saved")
                number_created_products += 1
                created_products_list.append(
                    [
                        product["product_title"],
                        product["product_sku"],
                        product["product_tag"],
                        date.today().strftime("%m-%d-%Y"),
                    ]
                )
            else:
                continue
        logging.info("{} product(s) created usccessfully".format(
            number_created_products
            )
        )
        # 2 Notify admins via email with created courses report
        # 2.1 Create CSV file from created products
        if number_created_products:
            text = "Number of created products in shopify: {} ".format(
                number_created_products
            )
            header = ["Product Name", "Product SKU", "Tahoe URL", "Created AT"]
            fp = NamedTemporaryFile(
                delete=False,
                prefix="created_product_",
                suffix=".csv",
                mode="w",
                dir="/tmp/",
            )
            writer = csv.writer(fp, quotechar='"', quoting=csv.QUOTE_ALL)
            writer.writerow(header)
            for created_product in created_products_list:
                writer.writerow(created_product)
            fp.flush()
            fp.close()
            data = open(fp.name, "rb").read()
            message = {
                "attachments": [
                    {
                        "content": base64.b64encode(data).decode("utf-8"),
                        "name": fp.name.split("/")[2],
                        "type": "text/csv",
                    }
                ],
                "from_email": "*****@*****.**",
                "from_name": "Appsembler Technical Support",
                "important": True,
                "subject": "You'r Shopify product creation report",
                "text": text,
                "to": [
                    {
                        "email": store_admin_email,
                        "name": store_admin_name,
                        "type": "to",
                    },
                    {
                        "email": "*****@*****.**",
                        "name": "Amir Tadrisi",
                        "type": "to",
                    },
                ],
            }
            if environment == "prod":
                mandrill_client.messages.send(message=message)
        return Response(
            "{} Product(s) got created".format(number_created_products),
            status=201
        )
    except Exception as e:
        logging.error(e)
        if environment == "prod":
            stackdriver_client.report_exception()