def export_products(self): """ This functions export products of the user to his shopify shop :return: """ export_products = "" products = self.env['product.template'].search([('create_uid', '=', self.env.user.id)]) shopify_products = shopify.Product.find(limit=250) for product in products: already_exist = False for shopify_product in shopify_products: if shopify_product.attributes['title'] == product.name: already_exist = True break if already_exist: continue export_products = export_products + product.name + " " new_product = shopify.Product() new_product.title = product.name new_product.body_html = product.description new_product.product_type = product.type product_variant = shopify.Variant({"title": "v1", "price": 123123}) new_product.variants = [product_variant] new_product.save() if export_products: raise osv.except_osv(("Products Export Success"), (export_products + " exported successfully")) else: raise osv.except_osv(("Products Export"), ("non product to export"))
def get_odoo_and_push(product_id): #get proxy server info = xmlrpc.client.ServerProxy('https://demo.odoo.com/start').start() url, db, username, password = \ info['host'], info['database'], info['user'], info['password'] #make proxy server? common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url)) #login uid = common.authenticate(db, username, password, {}) #get models models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url)) #parse first record print(product_id) models.execute_kw(db, uid, password, 'product.product', 'search', [[]]) product_id = int(product_id) [record] = models.execute_kw(db, uid, password, 'product.product', 'read', [[product_id]]) session = shopify.Session(app.config['SHOPIFY_STORE_DOMAIN'], "2020-10", app.config['SHOPIFY_PASSWORD']) shopify.ShopifyResource.activate_session(session) product = shopify.Product() product.title = record['name'] product.price = record['price'] product.weight = record['weight'], product.weight_unit = record['weight_uom_name'] product.save() return redirect('/')
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')
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())
def create(self, number_products): new_products = [] for counter in range(number_products): print("Generating Product: {0}".format(str(counter + 1))) print("current site mang", shopify.Product()._site) new_product = shopify.Product().create(self.generate_data(self)) if new_product.errors: # something went wrong! # TODO: we need to loop over our error messages and print them for message in new_product.errors.full_messages(): print("[ERROR] {0}".format(message)) break new_products.append(new_product) return new_products
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()
def to_shopify_object( self, existing_object: Optional[shopify.Product] = None ) -> shopify.Product: if existing_object: obj = existing_object else: obj = shopify.Product() for field in self.__fields__: if self.__getattribute__(field) is not None: obj.__setattr__(field, self.__getattribute__(field)) return obj
def post_product(self, record): product = shopify.Product() product.title = record.name product.handle = record.default_code or record.name product.body_html = record.description_sale or record.description_purchase or '' if record.attribute_line_ids: product.options = [{ 'name': attribute_line.attribute_id.display_name } for attribute_line in record.attribute_line_ids] product.variants = [] for local_variant in record.product_variant_ids: variant = { 'price': local_variant.lst_price, 'sku': local_variant.default_code or '', 'barcode': local_variant.barcode or '', 'inventory_management': 'shopify', } if record.attribute_line_ids: option_count = len(product.options) if option_count > 0: variant.update( option1=local_variant. product_template_attribute_value_ids.filtered( lambda self: product.options[0].get( 'name') in self.display_name).name) if option_count > 1: variant.update( option2=local_variant. product_template_attribute_value_ids.filtered( lambda self: product.options[1].get( 'name') in self.display_name).name) if option_count > 2: variant.update( option2=local_variant. product_template_attribute_value_ids.filtered( lambda self: product.options[2].get( 'name') in self.display_name).name) variant = shopify.Variant(variant) product.variants.append(variant) if self.ensure_response(product, 'save'): for local_variant, remote_variant in zip( record.product_variant_ids, product.variants): self.put_variant(local_variant, remote_variant.id, product) return True, product else: _logger.error(product.errors.errors) return False, product
def randomProduct(title): images = [] for i in range(random.randint(1, 4)): images.append(setUpImage(i + 1)) variants = [] variants.append(shopify.Variant({'price': random.randint(1, 100)})) attrs = {} attrs['title'] = title attrs['tags'] = ['bits and bobs, hats'] attrs['body_html'] = '<p>Hat in Grey. 100% Alpaca.</p>' attrs['image'] = images[0] attrs['images'] = images attrs['variants'] = variants product = shopify.Product(attributes=attrs) return product
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/")
def AddProducts(self): list_of_products = [] data = self.ReadFile() self.Infobox_Update('Trying To Add Products To Store..', 'normal') try: for ind in data.index: new_product = shopify.Product() new_product.title = data['title'][ind] new_product.product_type = data['product type'][ind] new_product.body_html = data['body'][ind] new_product.vendor = data['vendor'][ind] new_product.save() self.Infobox_Update( 'Product: ' + new_product.title + ' Added To Store Sucessfully', 'normal') list_of_products.append(new_product) return list_of_products except: raise RuntimeError("Could Not Add Product To Store.")
def export_product(self): """ This functions export products of the user to his shopify shop :return: """ shop_name = self.env.user.shop_name api_key = self.env.user.api_key api_password = self.env.user.api_password api_secret_key = self.env.user.api_secret_key shop_url = "https://%s:%s@%s.myshopify.com/admin" % ( api_key, api_password, shop_name) shopify.ShopifyResource.set_site(shop_url) shopify.Session.setup(api_key=api_key, secret=api_secret_key) exported_products = "" products = self.env['product.template'].search([('id', 'in', self.ids) ]) shopify_products = shopify.Product.find(limit=250) for product in products: already_exist = False for shopify_product in shopify_products: if shopify_product.attributes['title'] == product.name: already_exist = True break if already_exist: continue exported_products = exported_products + product.name + " " new_product = shopify.Product() new_product.title = product.name new_product.body_html = product.description new_product.product_type = product.type product_variant = shopify.Variant({"title": "v1", "price": 123123}) new_product.variants = [product_variant] new_product.save() if exported_products: raise osv.except_osv( ("Products Export Success"), (exported_products + " exported successfully")) else: raise osv.except_osv(("Products Export Message"), ("non product to export"))
def create_product(product): try: new_product = shopify.Product() new_product.title = product['title'] new_product.body_html = product['body_html'] new_product.handle = product['handle'] new_product.product_type = product['product_type'] new_product.tags = product['tags'] new_product.variants = create_variants(product['variants']) new_product.images = create_images(product['images']) new_product.options = create_options(product['options']) new_product.vendor = product['vendor'] save = new_product.save() if save: print('Saved') else: print('Not Saved') except ConnectionError: logging.error("Connection error occurred") return False except Exception as e: logging.exception(e)
def test_view(request): API_KEY = os.environ.get('SHOPIFY_API_KEY') PASSWORD = os.environ.get('SHOPIFY_API_PW') shop_url = os.environ.get('SHOPIFY_STORE_URL') % (API_KEY, PASSWORD) shopify.ShopifyResource.set_site(shop_url) shop = shopify.Shop.current() #Create a new product new_product = shopify.Product() new_product.title = "Burton Custom Freestyle 151" new_product.product_type = "Snowboard" new_product.vendor = "Burton" success = new_product.save() #returns false if the record is invalid #access a customer cust = shopify.Customer.find() spec = shopify.Customer.search(query='first_name:Jane') #print('cust', cust) return render(request, 'shopify_con/test.html', { 'cust': cust, 'spec': spec })
def upload(self): """Upload shit to shopify """ p = shopify.Product() p.title = self.name p.product_type = self.product_type p.body_html = self.build_description() p.vendor = self.vendor p.tags = list(sorted(self.tags)) p.options = self.build_options() p.variants = self.build_variants() if self.image_urls: p.images = [{'src': url} for url in self.image_urls] p.save() if p.errors: print p.errors.full_messages() raise RuntimeError("Failed to create product '%s'" % self.name) # create images afterwards, so we can associate them with variant IDs # (p.id doesn't exist until save()) self.create_images(p.id, p.variants)
def new_product(self, mill_name, style, short_description, full_description, category, color_index): """Create a new Shopify product with the given data.""" new_product = shopify.Product() title = short_description if not self._sanmar: title = "{} {}: {}".format(mill_name, style, short_description) if color_index > 0: color = "" if color_index >= len(self._color_groups): color = "Extended Colors {}".format(color_index) else: color = self._color_groups[color_index] title = "{}, {}".format(title, color) new_product.title = title desc_split = full_description.split( "|") if self._sanmar else full_description.split(";") new_product.body_html = "<ul><li>{}</li></ul>".format("</li><li>".join( [li.strip() for li in desc_split])) new_product.vendor = mill_name new_product.product_type = category new_product.save() new_product.variants = [] return new_product
def post(self, request, *args, **kwargs): reseller_id = kwargs['accountId'] dzero = decimal.Decimal(0) consignor_id = request.data.get('consignorId') category_id = request.data.get('categoryId') title = request.data.get('title') price = request.data.get('price', dzero) price = price if price else dzero retail_price = request.data.get('retailPrice', dzero) retail_price = retail_price if retail_price else dzero cost_net = request.data.get('costNet', dzero) cost_net = cost_net if cost_net else dzero quantity = request.data.get('quantity', 0) tag_quantity = request.data.get('tagQuantity', 0) item_fee = request.data.get('itemFee', dzero) item_fee = item_fee if item_fee else dzero allow_donate = request.data.get('allowDonate', False) featured_product = request.data.get('featuredProduct', False) shipping_handling = request.data.get('shippingHandling', dzero) shipping_handling = shipping_handling if shipping_handling else dzero web_fee = request.data.get('webFee', dzero) web_fee = web_fee if web_fee else dzero weight = request.data.get('weight', 0) width = request.data.get('width', 0) height = request.data.get('height', 0) date_received = request.data.get('dateReceived', datetime.datetime.now(datetime.timezone.utc)) date_updated = datetime.datetime.now(datetime.timezone.utc) list_ready = request.data.get('listReady', False) post_date = datetime.datetime.now(datetime.timezone.utc) description = request.data.get('description', '') reseller = Reseller.objects.filter(pk=reseller_id).first() consignor = Consignor.objects.filter(pk=consignor_id).first() category = Category.objects.filter(pk=category_id).first() item = Item( reseller=reseller, consignor=consignor, category=category, title=title, price=price, retail_price=retail_price, cost_net=cost_net, quantity=quantity, tag_quantity=tag_quantity, item_fee=item_fee, allow_donate=allow_donate, featured_product=featured_product, shipping_handling=shipping_handling, web_fee=web_fee, weight=weight, width=width, height=height, date_received=date_received, list_ready=list_ready, post_date=post_date, date_updated=date_updated, status='NEW' ) item.save() attributes = request.data.get('attributes') attributes = json.loads(attributes) for a in attributes: print(a) attribute_id = a['attributeId'] attribute = Attributes.objects.filter(pk=attribute_id).first() ItemAttributes(reseller=reseller, item=item, attribute=attribute, value=a['value']).save() session = shopify.Session(reseller.domain, '2019-04', reseller.shopify_access_token) shopify.ShopifyResource.activate_session(session) new_product = shopify.Product() new_product.title = title new_product.product_type = category.json()['displayName'] description = """ <strong> {0} </strong> <br /><br /> """.format(description) new_product.save() variant_object = { "product_id": new_product.id, "inventory_quantity": str(quantity), "price": str(price), "weight": weight } for a in attributes: attribute_id = a['attributeId'] attribute = Attributes.objects.filter(pk=attribute_id).first() new_product.add_metafield(shopify.Metafield({ 'namespace': 'attribute', 'key': attribute.json()['name'], 'value': a['value'], 'value_type': 'string', })) variant_object[attribute.json()['name']] = a['value'] description = """ {0} <strong> {1} </strong>: {2} <br /> """.format(description, attribute.json()['name'], a['value']) variant = shopify.Variant(variant_object) variant.save() new_product.body_html = description new_product.add_variant(variant) new_product.save() item.description = description item.save() for image in request.data.getlist('image'): file_type = image.name.rsplit('.', 1)[1] photo = ItemPhotos(reseller=reseller, item=item, file_type=file_type) photo.save() photo_json = photo.json() content_type = "image/" + photo.file_type response = self.spaces_client.put_object( Body=image, # Path to local file Bucket=photo_json['bucket'], # Name of Space Key=photo_json['url'], ACL='public-read', ContentType=content_type) return Response(status=status.HTTP_201_CREATED)
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()}')")
start = search.find('url("') + len('url("') end = search.find('");') imgurl = search[start:end] imgurl = imgurl.replace('225', '1600') print('image source: ', imgurl) # path for description iframe = soupP.find('iframe')['src'] iframe = iframe.replace('amp;', '') result2 = requests.get(iframe) descHTML = result2.text print('description obtained') ########################### SHOPIFY ############################# new = shopify.Product() enc = urllib.parse.quote(title) r = requests.get(shop_url + '/products.json?title=' + enc) # Handle errors if r.status_code == 401 or r.status_code == 400: print(r) print( 'ERROR: Invalid Shopify credentials. Please check if shop name, API key, and password are correct!' ) exit(1) if not r.json()['products']: # NEED title, decscription, media, pricing(price), charge tax on product, quantity (availible), weight
def add_new_kit(kit_variant): # 2 cases # 1) Is a variant # Tags tags_to_add = [] # Size tags_to_add.append("Size_" + kit_variant.get_size()) tags_to_add.append(kit_variant.get_tire()) tags_to_add.append(kit_variant.get_wheel()) if kitTools.has_variants(kit_variant): product_id = kitTools.find_product_id(kit_variant) new_kit_product = shopify.Product.find(product_id) variant = shopify.Variant({ 'price': kit_variant.get_msrp(), 'option1': kit_variant.get_wheel(), 'option2': kit_variant.get_tire(), 'sku': "a", 'position': 1, 'inventory_policy': "continue", 'fulfillment_service': "manual", 'inventory_management': "shopify", 'inventory_quantity': 1, 'taxable': False, 'weight': 0, 'weight_unit': "g", # g, kg 'requires_shipping': True }) # Get tags already put in tags = Tags() tags.string_to_tags(new_kit_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_kit_product.tags = tags.tags_to_string() new_kit_product.variants.append(variant) new_kit_product.save() kitTools.add_kit(product_id, kit_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_kit_product = shopify.Product() new_kit_product.options = [{'name': 'Wheel'}, {'name': 'Tire'}] new_kit_product.title = kit_variant.get_kit_name() new_kit_product.vendor = "Racks Deep Custom Performance" new_kit_product.product_type = "Kits" new_kit_product.body_html = """<b>%s</b> <h1>All Kits come mounted with new lugnuts</h1> """ % (kit_variant.get_kit_name()) variant = shopify.Variant({ 'price': kit_variant.get_msrp(), 'option1': kit_variant.get_wheel(), 'option2': kit_variant.get_tire(), 'sku': "a", 'position': 1, 'inventory_policy': "continue", 'fulfillment_service': "manual", 'inventory_management': "shopify", 'inventory_quantity': 1, 'taxable': False, 'weight': 0, 'weight_unit': "g", # g, kg 'requires_shipping': True }) new_kit_product.variants = [variant] new_kit_product.tags = """WheelPros, Kits """ # Get tags already put in tags = Tags() tags.string_to_tags(new_kit_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_kit_product.tags = tags.tags_to_string() #image = shopify.Image() #file_name = "%s" % (wheel_variant.get_wheel_image()) #if ShopifyTools.is_image_and_ready(file_name): # image.src = file_name # else: # print(wheel_variant.get_upc) # print(wheel_variant.get_style_description()) # print("-----------------") # new_wheel_product.images = [image] new_kit_product.save() kitTools.add_kit(new_kit_product.id, kit_variant) if new_kit_product.errors: # something went wrong, see new_product.errors.full_messages() for example print(new_kit_product.errors.full_messages())
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()}')" )
shop_url = "https://%s:%[email protected]/admin" % (API_KEY, SHARED_SECRET) shopify.ShopifyResource.set_site(shop_url) shopify.Shop() # Get the current shop shop = shopify.Shop.current() # Get a specific product product = shopify.Product.find(179761209) # Create a new product new_product = shopify.Product() new_product.title = "Burton Custom Freestyle 151" new_product.product_type = "Snowboard" new_product.vendor = "Burton" success = new_product.save() #returns false if the record is invalid # or if new_product.errors: #something went wrong, see new_product.errors.full_messages() for example # Update a product product.handle = "burton-snowboard" product.save() # Remove a product product.destroy()
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()
def get_all_products(): pd=shopify.Product() pd = requests.get(urlstart + "/products/count.json",auth=(keyp,passp)) print(pd)
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()
def createNewShopifyProductAndVariants( product ): #shopify.ShopifyResource.activate_session(session) logger.debug('I think the product handle is {}'.format(product['Handle'])) import pprint logger.debug( pprint.pformat(product)) if len(shopify.Product.find(handle=product['Handle'])) > 0: logger.warning('tried to add product with handle {} but that product already exists'.format(product['Handle'])) abort(400) pr = shopify.Product() pr.title = product['Title'] fmt = lambda key,value: { "key": key, "value": value, "value_type": "string", # TODO do this right "namespace": "Namespace"} pr.metafields = [ fmt('Manufacturer', product['Manufacturer']), fmt('MPN', product['MPN']), fmt('dimX', product['dimX']), fmt('dimY', product['dimY']), fmt('dimZ', product['dimZ']) ] variants = [] for v in product['variants']: va = { 'option1': v['Option1 Value'], 'inventory_management': 'shopify', 'inventory_policy': 'continue', 'weight': product['Weight(g)'], 'weight_unit': 'g', 'metafields': [ fmt('condition-notes', v['condition-notes']), fmt('Ownership', v['Ownership'] ), fmt('Sunk-cost', v['Sunk-cost'] ) ] } variants.append(va) pr.variants = variants pr.options = [ { "name": "Condition", "position": 1, "values": ["New", "Used - Like new", "Used - Good", "Used - Fair", "Used - as-is/for parts"]} ] logger.debug('Trying to save product to Shopify...') if pr.save() is False: message = 'Couldn\'t save product {}. Error messages: {}...'.format( product['Handle'], pr.errors.full_messages() ) logger.error(message) raise RuntimeError(message) else: logger.info('Successfully created product id {} - {}'.format(pr.id, pr.handle)) logger.debug('Trying to set barcodes for variants...') for i,var in enumerate(product['variants']): v = pr.variants[i] if v.option1 == var['Option1 Value']: # this is the right new/used variant (avoid counting errors) v.barcode = var['barcode'] logger.debug('Assigned barcode {} to variant {}...'.format(v.barcode, v.option1)) pr.save() # TODO second round of error checking on this one qtystr = ','.join( [ str(product['variants'][i]['Option1 Value']) + "," + str(product['variants'][i]['qty-reported']) for i in range(len(product['variants']))]) logger.info('Reported quantities: {}'.format(qtystr)) return((id,product))
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()