Ejemplo n.º 1
0
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)
Ejemplo n.º 2
0
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"
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
	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
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
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')
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
    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)
Ejemplo n.º 9
0
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}
Ejemplo n.º 10
0
    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)
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;
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
from sqlalchemy.exc import DBAPIError
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound, HTTPNotFound, HTTPBadRequest
from pyramid.security import NO_PERMISSION_REQUIRED, remember, forget
from ..sample_data import MOCK_DATA
import requests
import json

from ..models import Account
from semantics3 import Products

sem3 = Products(api_key="SEM3B4C97C14B003A87822E95D682C8847F2",
                api_secret="ZWVmOGUxNDg1YjM1ZTNjZjMwNTI1Zjk4MjA5MThhNTg")


@view_config(route_name='home',
             renderer='../templates/base.jinja2',
             request_method='GET',
             permission=NO_PERMISSION_REQUIRED)
def index_view(request):
    """
    Directs user to the home template
    """
    return {}


@view_config(route_name='about',
             renderer='../templates/about_us.jinja2',
             request_method='GET',
Ejemplo n.º 14
0
    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
Ejemplo n.º 15
0
    import eventlet
    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)
Ejemplo n.º 16
0
import food2fork as f2f
import world_openfoodfacts as woff
import ingredients_parser as ip
import utils as u
import json, sys
import food_ndtv_parser as food_ndfv
from semantics3 import Products
import time

sem3 = Products(api_key="SEM37B78A6306695816904F3BB8C677F71D8",
                api_secret="OTg4OWJiN2ZhZjc0Y2Q5ZjJhODIyNDE2MzhhZDM2ZmY")


def f2f_api():
    result = f2f.send_requests(11, 16)
    links = f2f.parse_api_response(result)
    recipes = []
    for website in f2f.valid_websites.keys():
        data = f2f.get_recipes_html(links[website])
        recipes.extend(f2f.valid_websites[website](data))
    d = dict()
    d["count"] = len(recipes)
    d["recipies"] = recipes
    # print(d)
    u.write(json.dumps(d), "food2fork")


def ing_with_categ():
    ingredients_with_category = food_ndfv.parse()
    u.write(json.dumps(ingredients_with_category), "ingredients_with_category",
            "")
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
 def __init__(self):
     self.products = Products(api_key="xx", api_secret="xx")
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
from flask import Flask, render_template, request, session, url_for, redirect
import json
import datetime
from copy import deepcopy
from sqlite3 import connect
from hashlib import sha1
from semantics3 import Products

sem3 = Products(api_key="SEM3C4DC74D42480F5F4C1CD26C2108854E6",
                api_secret="YmVkZGQ1YWY1NTQxOThlZTE5Y2FlMDU1Nzc2MTlmMDQ")
f = "data/database.db"


def get_median(l):
    l = sorted(l)
    if len(l) % 2 == 1:
        return l[len(l) // 2]
    return (l[len(l) // 2] + l[len(l) // 2 - 1]) / 2


def insert_interval(l, interval):
    for i in range(len(l)):
        if interval[1] <= l[i][1]:
            l.insert(i, interval)
            return l
    l.append(interval)
    return l


def to_datetime(d):
    return datetime.datetime.fromtimestamp(
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
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 {}
Ejemplo n.º 23
0
    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']
Ejemplo n.º 24
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}
Ejemplo n.º 25
0
 def __init__(self):
     self.api_key = 'SEM30A3983D93A26181838BA0FA228979B01'
     self.api_secret = 'OWFiNmE3YTU2NDljNDliNDU4ZDczZTk1ZmU3MTgzMDE'
     self.wrapper = Products(api_key=self.api_key,
                             api_secret=self.api_secret)
Ejemplo n.º 26
0
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)
Ejemplo n.º 27
0
     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'])
Ejemplo n.º 28
0
# Here I am importing the "decimal" module, which will help me find the average price of the search later.
from decimal import Decimal

# Here I am importing the "textblob" module which will help me to find the sentiment of the string by first "globbing" the string together.
from textblob import TextBlob

# Here I am importing all of the external functions from my "functions.py" file, which I will use later.
from functions import input_sentiment, crosscheck_email, character_counter

# Code Citation: Semantics 3 API Documentation
# URL: https://docs.semantics3.com/reference#keyword-api-1
# Author: Semantics3
# Accessed on: 4/3/18
# Purpose of code: The API key and secret will be passed along with the request, allowing me to access a response.
sem3 = Products(api_key="SEM3D4E92E7495711694BF8E16042CB789B7",
                api_secret="NjJmYWI3ZDQyZGZmMzk4ZjkwNjMzNWUxZjM0YjU0ODQ")

# I defined all of the global variables below.
user_list = []

email_list = []

password_list = []

price_list = []

username = ""

return_user = ""

return_item_num = ""
Ejemplo n.º 29
0
from semantics3 import Products
import unittest
from os import environ

sem3 = Products(api_key=environ["SEM3_API_KEY"],
                api_secret=environ["SEM3_API_SECRET"])


class TestProductAPI(unittest.TestCase):
    """Docstring for TestProductAPI. """
    def test_get_products(self):
        """@todo: Docstring for test_get_products.
        :returns: @todo

        """
        sem3.products_field("search", "iphone")
        results = sem3.get_products()
        self.assertEqual(results['code'], 'OK')
        sem3.clear_query()

    def test_upc_query(self):
        """@todo: Docstring for test_upc_query.
        :returns: @todo

        """
        pass
        sem3.products_field("upc", "883974958450")
        sem3.products_field("field", ["name", "gtins"])
        results = sem3.get_products()
        self.assertEqual(results['code'], 'OK')
        sem3.clear_query()
Ejemplo n.º 30
0
from semantics3 import Products
import unittest

sem3 = Products(api_key="", api_secret="")


class TestProductAPI(unittest.TestCase):
    """Docstring for TestProductAPI. """
    def test_get_products(self):
        """@todo: Docstring for test_get_products.
        :returns: @todo

        """
        sem3.products_field("search", "iphone")
        results = sem3.get_products()
        self.assertEqual(results['code'], 'OK')
        sem3.clear_query()

    def test_upc_query(self):
        """@todo: Docstring for test_upc_query.
        :returns: @todo

        """
        pass
        sem3.products_field("upc", "883974958450")
        sem3.products_field("field", ["name", "gtins"])
        results = sem3.get_products()
        self.assertEqual(results['code'], 'OK')
        sem3.clear_query()

    def test_url_query(self):
Ejemplo n.º 31
0
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':
Ejemplo n.º 32
0
import requests, json
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from semantics3 import Products
import MySQLdb

app = Flask(__name__)

#Set up a client to talk to the Semantics3 API using your Semantics3 API Credentials
sem3 = Products(api_key="SEM322EF6FCE667BE9ED88826363DE85E0A2",
                api_secret="NmI4OTU5ZmVjZTVkZDNlODhmYmZmN2Q2ZTkyMmQ2OTY")

#Configure the Database
app.config[
    'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@sql9.freemysqlhosting.net:3306/sql9240288'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class WishList(db.Model):
    #__tablename__ = "wish_list"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    price = db.Column(db.String(10))
    url = db.Column(db.String(1000))


"""
	Takes in a string input and
	return it as a dictionary.
	Used to add to a databse