class Base(object): #Defining api key in constructor def __init__(self): self.products = Products(api_key="xx", api_secret="xx") #Getting product results from constructor def get_result_example(self): self.products.products_field("search", "Samsung Galaxy") results = self.products.get_products() return results def user_selection(self): print("1. Try Sample result for api") print("2. Get results in a csv file") print("3. Get results in a file(JSON Pretty)") print("4. Get results in a file(Normal JSON)") self.usr_input = input("Enter any choice") #return self.usr_input def switch_selection(self): if self.usr_input == 1: print b.get_result_example() elif self.usr_input == 2: print b.get_result_example() elif self.usr_input == 3: print b.get_result_example() elif self.usr_input == 3: print b.get_result_example() else: print "Please enter a number from 1 to 4"
def make_query(item_name): products = Products( api_key='SEM3A92F1C506BB40F217AA3716D7C9A8815', api_secret='ZGU0MWJiNjY1ZTY1OTgxZDVhODFiYWNkYzNkOTBjZjA') products.products_field('name', item_name) result_query = products.get_products() code = result_query['code'] result_list = result_query['results'] result_count = result_query['results_count'] return code, result_list, result_count
def make_query(item_name): products = Products( api_key = 'SEM3A92F1C506BB40F217AA3716D7C9A8815', api_secret = 'ZGU0MWJiNjY1ZTY1OTgxZDVhODFiYWNkYzNkOTBjZjA') products.products_field('name', item_name) result_query = products.get_products() code = result_query['code'] result_list = result_query['results'] result_count = result_query['results_count'] return code, result_list, result_count
def import_shoes(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Shoe = apps.get_model("product", "Product") products = Products(api_key = "SEM383288C8F0304F7BB107E2E110B0420D3",api_secret = "MGYwZjgxZTVkOTVmZmY5OTEwYzlkMWI4MDAxMzk3YjA") products.products_field( "name", "Shoes" ) products.products_field( "limit", 100 ) results = products.get_products(); resultarr = results['results']; count = 1; for i,var in enumerate(resultarr): s = Shoe(id = count, name= var['name'], price= Decimal(var['price']), stock= 1, description= var['category']); s.save() count=count+1;
def user_profile(request): sem3 = Products( api_key = "SEM3CCB4BBBB383C73986C4B27B9BE4B3088", api_secret = "YmJjY2M1YzFlMGM0ZTg1OTdlNDFkYmY5MmRmZTg2ZDk" ) if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): form.save() searchInput = form.cleaned_data.get('input') sem3.products_field("search", searchInput) results = sem3.get_products() return render(request, 'user_profile.html', results) else: return render(request, 'user_profile.html')
def product_results(request, current_search): #variable setups products = Products( api_key = "SEM34D405CE2A6F4715E79457D08A21B4CEE", api_secret = "NmI0ZDkwZmJhMGVkNGU1NWI5Y2ZmYWNkMjgzNzUyZDg" ) current_user = User.objects.get(username=request.user) form = ProductSearchForm(initial={'Search': current_search}) #get user's last search and feed to Semantics3, render results query = products.products_field("name", current_search) response = products.get_products() results = response["results"] #get search query, add to database and session, redirect if request.method == 'GET': form = ProductSearchForm(request.GET) if form.is_valid(): this_search = form.cleaned_data['search'] request.session["search"] = this_search current_search = Search(query=this_search, user=current_user.id) current_search.save() return HttpResponseRedirect('/shopping/results/'+this_search) CONTEXT = {'results': results, 'search': current_search, 'form': form} return render(request, 'product_search/shopping_results.html', CONTEXT)
def isUpcExist(code): product = Products(SEMANTIC_PUBLIC, SEMANTIC_SECRET) product.products_field("upc", str(code)) results = product.get_products() # a = ['CD','DVD', 'CD()'] # yes = results['results'][0]['format'] # count = 0 # for x in range(1,len(a)): # if(yes == a[x]): # print('{} == {}'.format(a[:],yes)) # count += 1 # else: # print('Error') if results['results_count'] == 1: return results, True else: print("not exist") return results, False
def getData(self): # Set up a client to talk to the Semantics3 API using your Semantics3 API Credentials sem3 = Products(api_key=self.apikey, api_secret=self.apisecret) sem3.products_field("site", self.site) sem3.products_field("sitedetails_display", ("include", [self.site])) sem3.products_field("offset", self.offset) sem3.products_field("limit", self.limit) results = sem3.get_products() ds = json.dumps(results) self.writeData(ds) return ds
def getData(self): # Set up a client to talk to the Semantics3 API using your Semantics3 API Credentials sem3 = Products(api_key = self.apikey, api_secret = self.apisecret) sem3.products_field("site", self.site) sem3.products_field("sitedetails_display", ("include", [self.site])) sem3.products_field("offset", self.offset) sem3.products_field("limit", self.limit) results = sem3.get_products() ds = json.dumps(results) self.writeData(ds) return ds
def import_shoes(apps, schema_editor): # We can't import the Person model directly as it may be a newer # version than this migration expects. We use the historical version. Shoe = apps.get_model("product", "Product") products = Products( api_key="SEM383288C8F0304F7BB107E2E110B0420D3", api_secret="MGYwZjgxZTVkOTVmZmY5OTEwYzlkMWI4MDAxMzk3YjA") products.products_field("name", "Shoes") products.products_field("limit", 100) results = products.get_products() resultarr = results['results'] count = 1 for i, var in enumerate(resultarr): s = Shoe(id=count, name=var['name'], price=Decimal(var['price']), stock=1, description=var['category']) s.save() count = count + 1
class SemanticsPuller(object): def __init__(self): self.api_key = 'SEM30A3983D93A26181838BA0FA228979B01' self.api_secret = 'OWFiNmE3YTU2NDljNDliNDU4ZDczZTk1ZmU3MTgzMDE' self.wrapper = Products(api_key=self.api_key, api_secret=self.api_secret) def get_product(self, upc): self.wrapper.products_field("upc", upc) resp = self.wrapper.get_products() if resp['results']: results = resp['results'][0] filtered_results = { k: v for k, v in results.items() if k in ['name', 'upc', 'images'] } filtered_results['images'] = filtered_results['images'][0] return filtered_results else: # raise Exception('Could not find the product') return {'upc': upc, 'images': None, 'name': None, 'quantity': 0}
def get_recommendations(name, brand=None): k = keys.Keys() # categories = Categories( # api_key = k.get_semantics_api_key(), # api_secret = k.get_semantics_secret_key() # ) products = Products(api_key=k.get_semantics_api_key(), api_secret=k.get_semantics_secret_key()) products.products_field("search", name) if brand != None: products.products_field("brand", brand) products.products_field("variation_includeall", 0) products.products_field("limit", 10) results = products.get() output = [] for r in results["results"]: data = {} try: data['image'] = r["images"][0] except: pass data['url'] = r['sitedetails'][0]["url"] try: data['price'] = r['sitedetails'][0]["latestoffers"][0]["price"] except: pass try: data['brand'] = r['brand'] except: pass data['title'] = r['name'] data['status'] = True output.append(data) return {"results": output}
def post(self, request, *args, **kwargs): product_serializer = ProductSerializer(data=request.data) if product_serializer.is_valid(): product_serializer.save() upc = product_serializer.data['upc'] ean = product_serializer.data['ean'] sem3 = Products( api_key="SEM358802643C8595EA80A4BA5F74DB35FD9", api_secret="ZDhkMDJiNmEzMzdlMzVmZmQwNmNmZGVhODE4ZjQ4ZGQ") if ean or len(ean) > 5: print("EAN in") sem3.products_field("ean", ean) elif upc or len(upc) > 5: print("UPC in") sem3.products_field("upc", upc) sem3.products_field("fields", ["name", "gtins"]) p = "product not found" # Run the request try: results = sem3.get_products() print(results) p = results['results'][0]['name'] except: print('An error occured.') # View the results of the request print(p) return Response({ "upc": product_serializer.data, "result": p }, status=status.HTTP_201_CREATED) else: return Response(product_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
SEM3KEY y SEM3S son la API key y el API secret que se obtiene al darse de alta como usuario. La version demo permite hacer 500 queries diarias por usuario. :Authors: bejar :Version: :Created on: 25/02/2016 15:27 """ from semantics3 import Products from AgentUtil.APIKeys import SEM3KEY, SEM3SECRET __author__ = 'bejar' sem3 = Products( api_key=SEM3KEY, api_secret=SEM3SECRET ) sem3.products_field("search", "iphone") # Run the request results = sem3.get_products() # View the results of the request print results['results']
sys.modules['httplib2'] = eventlet.import_patched('httplib2') print "[Optional Import] Using eventlet" except Exception: print "[Optional Import] Not using eventlet" from semantics3 import Semantics3Request from semantics3 import Products from semantics3 import Categories from semantics3 import Offers import pprint api_key = "" api_secret = "" pp = pprint.PrettyPrinter() products = Products(api_key, api_secret) products.products_field("cat_id", 4992) products.products_field("brand", "Toshiba") products.products_field("weight", "gte", 1000000) products.products_field("weight", "lt", 1500000) products.products_field("sitedetails", "name", "newegg.com") products.products_field("sitedetails", "latestoffers", "currency", "USD") products.products_field("sitedetails", "latestoffers", "price", "gte", 100) products.cache(5) for i in products.iter(): pass # Build the query products.categories_field("cat_id", 4992) # Execute the query
def product_results( request, current_search, template="shopping/shopping_results.html", page_template="shopping/products.html" ): # variable setups products = Products( api_key="SEM34D405CE2A6F4715E79457D08A21B4CEE", api_secret="NmI0ZDkwZmJhMGVkNGU1NWI5Y2ZmYWNkMjgzNzUyZDg" ) current_user = User.objects.get(username=request.user) form = ProductSearchForm # get user's last search and feed to Semantics3, render results query = products.products_field("name", current_search) products.get_products() # iterate over products, add to results list (position 0 in results) results = [] for i in products.iter(): results.append(i) if len(results) == 10: break # get lowest prices for each item, add to separate list (position 1 in results) lowest_prices = [] for i in results: prices = [] for store in i["sitedetails"]: prices.append("%.02f" % float(store["latestoffers"][0]["price"])) prices = sorted(prices) lowest_prices.append(prices[0]) results_master = zip(results, lowest_prices) # Django Endless Pagination (Twitter Style Reload) if request.is_ajax(): request_page = utils.get_page_number_from_request(request) offset = (request_page - 1) * 10 products.products_field("offset", offset) products.get_products() # iterate over products, apply an offset based on page number, add to results list (position 0 in results_master) results = [] for i in products.iter(): results.append(i) if len(results) == 10 + offset: break # get lowest prices for each item, add to separate list (position 1 in results_master) lowest_prices = [] for i in results: prices = [] for store in i["sitedetails"]: prices.append("%.02f" % float(store["latestoffers"][0]["price"])) prices = sorted(prices) lowest_prices.append(prices[0]) results_master = zip(results, lowest_prices) template = page_template # get search query, add to database and session, redirect if request.method == "GET": form = ProductSearchForm(request.GET) if form.is_valid(): this_search = form.cleaned_data["search"] current_search = Search(query=this_search, user=current_user) current_search.save() return HttpResponseRedirect("/shopping/results/" + this_search) if request.method == "POST": return HttpResponseRedirect("/overview/") CONTEXT = { "results": results_master, "search": current_search, "form": form, "page_template": page_template, "lowest_prices": lowest_prices, } return render(request, template, CONTEXT)
from semantics3 import Products sem3 = Products( api_key = "SEM3188CBEA0C536322303E7C24718D47A3B", api_secret = "ZDI1NWU4NTQ3M2M4MjJiZDdlMWNlNDBmMTM0MTQ4OGU" ) userInputProduct = input("What product would you like to know about: ") sem3.products_field("search", userInputProduct) results = sem3.get_products() print(results)
pip install semantics3 SEM3KEY y SEM3S son la API key y el API secret que se obtiene al darse de alta como usuario. La version demo permite hacer 500 queries diarias por usuario. :Authors: bejar :Version: :Created on: 25/02/2016 15:27 """ from semantics3 import Products from AgentUtil.APIKeys import SEM3KEY, SEM3SECRET import pprint __author__ = 'bejar' if __name__ == '__main__': sem3 = Products(api_key=SEM3KEY, api_secret=SEM3SECRET) sem3.products_field("search", "iphone") # Run the request results = sem3.get_products() # View the results of the request pprint.pprint(results['results'])
class Command(BaseCommand): # string with numbers, max length is 14 chars UPC_REGEXP = re.compile('^\d{1,14}$') option_list = ( Option('--limit', dest='limit', type=int),) def run(self, limit=None): app.logger.info('Run create missing products.') self.product_finder = SemanticProducts(**app.config['SEMANTICS3']) submissions = self._get_submissions() app.logger.debug('Found {} submission without product.'.format( submissions.count())) products_wrong_category = [] if limit: app.logger.debug('Applied limit: {}.'.format(limit)) submissions = submissions.limit(limit) for submission in submissions: task = submission.assignment.task app.logger.debug('Processing submission {}.'.format(submission.id)) app.logger.debug('Retailer {}, category: {}.'.format( task.retailer_id, task.retsku_category_id)) if task.retailer_id is None: app.logger.debug('Task retailer id should be specified.') continue gtin = None if self.UPC_REGEXP.match(submission.scanned_upc): gtin = gtin_validator.validate_GTIN(submission.scanned_upc) if gtin is None: app.logger.debug( 'Submission upc {} is not valid GTIN'.format( submission.scanned_upc)) continue product = self._get_product(task.retailer_id, gtin, task.retsku_category_id, submission) if product is None: app.logger.debug('Couldn\'t create product.') continue if product.retsku_category_id != task.retsku_category_id: product.task_retsku_category_id = task.retsku_category_id products_wrong_category.append(product) if not product.retsku_product_id: self._update_retsku_product_id(product) self._add_log(submission.id, 'update submission', submission.ret_sku_id, product.ret_sku_id) submission.product = product submission.retsku_product_id = product.retsku_product_id app.logger.debug( 'Updating ret_sku_id: {}, retsku_product_id: {}'.format( product.ret_sku_id, product.retsku_product_id)) db.session.commit() if products_wrong_category: html = render_template('email/missing_products.html', products=products_wrong_category) email_service.send_mail(app.config['DEFAULT_MAIL_TO'], 'Products with categories mismatch', html) def _get_submissions(self): return Submission.query.filter( Submission.ret_sku_id == None, Submission.scanned_upc != None, Submission.barcode != None).order_by( Submission.updated_at.desc()) def _get_product(self, retailer_id, gtin, retsku_category_id, submission): products = Product.query.filter( Product.retailer_id == retailer_id, Product.gtin == gtin).all() if not products: products = Product.query.filter( Product.retailer_id == retailer_id, Product.barcode == submission.barcode).all() if products: # if we have list use first or try to find with the same values for p in products: if p.gtin == gtin and p.barcode == submission.barcode: product = p break else: product = products[0] if product.barcode != submission.barcode: app.logger.debug( 'Updating barcode for {}. Old: {}, new: {}.'.format( product.ret_sku_id, product.barcode, submission.barcode)) self._add_log(product.ret_sku_id, 'update barcode', product.barcode, submission.barcode) product.barcode = submission.barcode db.session.commit() if product.gtin != gtin: app.logger.debug( 'Updating GTIN for {}. Old: {}, new: {}.'.format( product.ret_sku_id, product.gtin, gtin)) self._add_log(product.ret_sku_id, 'update gtin', product.gtin, gtin) product.gtin = gtin db.session.commit() else: product = self._create_product(retailer_id, gtin, retsku_category_id, submission) return product def _create_product(self, retailer_id, gtin, retsku_category_id, submission): if submission.brand is None or submission.model is None: semantics_info = self._get_semantics_info(submission.scanned_upc) else: semantics_info = {} # get or create brand brand_name = submission.brand or semantics_info.get('brand') if not brand_name: return None brand_name = brand_name.strip() brand = Brand.query.filter( func.lower(Brand.brand_name) == func.lower(brand_name)).first() if not brand: brand = Brand(brand_name=brand_name) db.session.add(brand) db.session.commit() self._add_log(brand.brand_id, 'create new brand', None, None) model = submission.model or semantics_info.get('model') or gtin product = Product(retailer_id=retailer_id, retsku_category_id=retsku_category_id, gtin=gtin, barcode=submission.barcode, external_product_code=gtin, model_name=model, brand=brand, semantic_id=semantics_info.get('semantic_id')) db.session.add(product) db.session.commit() self._add_log(product.ret_sku_id, 'create new product', None, None) return product def _update_retsku_product_id(self, product): result = retsku_api.get_retsku_product_id( brand_name=product.brand.brand_name, semantic_id=product.semantic_id, model_name=product.model_name, product_code=product.external_product_code, gtin=product.gtin) if result: self._add_log(product.ret_sku_id, 'update retsku product id', product.retsku_product_id, result['retsku_product_id']) product.retsku_product_id = result['retsku_product_id'] product.matcher_type = result['matcher_type'] # yr: do we need update retsku_category_id? db.session.commit() def _add_log(self, item_id, action, old_value, new_value): action = LogAction(item_id=item_id, action=action, old_value=old_value, new_value=new_value) db.session.add(action) db.session.commit() def _get_semantics_info(self, upc): self.product_finder.clear_query() self.product_finder.products_field('upc', upc) try: json_data = self.product_finder.get() if json_data.get('results', None): item = json_data['results'][0] return { 'semantic_id': item.get('sem3_id'), 'brand': item.get('brand', item.get('manufacturer')), 'model': item.get('model', item.get('mpn'))} return {} except (ValueError, Semantics3Error): return {}
from semantics3 import Products sem3 = Products(api_key="SEM310D8563D0E07BA3AC280829F8076605D", api_secret="ZTliZjI1NTg5ZDQ2ZjdhNDMyNmRmMTc4Mjg3NjJmN2M") product_list = ['laptop', 'phone'] results = [] all_products = [] for product in product_list: sem3.products_field("search", product) results = sem3.get_products() if product == 'laptop': for i, p in enumerate(results['results']): title = results['results'][i]['name'] price = results['results'][i]['price'] if 'color' in results['results'][i].keys(): color = results['results'][i]['color'] else: color = None image = results['results'][i]['images'] url = results['results'][i]['sitedetails'][0]['url'] product_data = { 'product': 'Laptop', 'title': title, 'price': price, 'color': color, 'image': image, 'url': url, } if product == 'phone':
class Command(BaseCommand): # string with numbers, max length is 14 chars UPC_REGEXP = re.compile('^\d{1,14}$') option_list = ( Option('--limit', dest='limit', type=int),) def run(self, limit=None): app.logger.info('Run update submissions product.') self.product_finder = SemanticProducts(**app.config['SEMANTICS3']) submissions = self._get_submissions() app.logger.debug('Found {} submission without product.'.format( submissions.count())) not_linked_subs = [] if limit: app.logger.debug('Applied limit: {}.'.format(limit)) submissions = submissions.limit(limit) for submission in submissions: app.logger.debug('Processing submission {}.'.format(submission.id)) gtin = None if self.UPC_REGEXP.match(submission.scanned_upc): gtin = gtin_validator.validate_GTIN(submission.scanned_upc) if gtin is None: app.logger.debug( 'Submission upc {} is not valid GTIN'.format( submission.scanned_upc)) not_linked_subs.append(submission) continue product_info = self._get_product_info(gtin) if not product_info: not_linked_subs.append(submission) continue retsku_product_id = self._get_retsku_product_id( gtin, product_info['brand'], product_info['model']) if not retsku_product_id: not_linked_subs.append(submission) continue submission.retsku_product_id = retsku_product_id self._add_log(submission.id, 'update submission retsku product id', None, retsku_product_id) app.logger.debug(('Updating retsku_product_id: {}' '').format(submission.retsku_product_id)) db.session.commit() if not_linked_subs: html = render_template('email/submissions_without_products.html', submissions=not_linked_subs) email_service.send_mail(app.config['DEFAULT_MAIL_TO'], 'Submissions without retsku_product_id', html) def _get_submissions(self): return Submission.query.filter( Submission.ret_sku_id == None, Submission.retsku_product_id == None, Submission.scanned_upc != None, Submission.scanned_upc != '').order_by( Submission.updated_at.desc()) def _get_retsku_product_id(self, gtin, brand, model): result = retsku_api.get_retsku_product_id( brand_name=brand, model_name=model, gtin=gtin) if result: return result['retsku_product_id'] return None def _add_log(self, item_id, action, old_value, new_value): action = LogAction(item_id=item_id, action=action, old_value=old_value, new_value=new_value) db.session.add(action) db.session.commit() def _get_product_info(self, upc): product_info = self._get_product_match_info(upc) return product_info or self._get_semantics_info(upc) def _get_product_match_info(self, upc): info = retsku_api.get_products_info(upc) if info: return {'brand': info['brand'], 'model': info['model']} return None def _get_semantics_info(self, upc): self.product_finder.clear_query() self.product_finder.products_field('upc', upc) try: json_data = self.product_finder.get() if json_data.get('results', None): item = json_data['results'][0] return { 'brand': item.get('brand', item.get('manufacturer')), 'model': item.get('model', item.get('mpn'))} return None except (ValueError, Semantics3Error): return None