Beispiel #1
0
def main(sellerApi, category):
    # Carregando as ofertas a serem adicionadas
    offers = IOUtil.json_to_dic('to_add.json', category['id'])

    # Verifica se tem alguma oferta
    if len(offers) == 0:
        print("No offer to add.")
        return

    # Buscando e preenchendo o GTIN
    if category['gtin']:
        offers = sellerApi.fill_gtin(offers, category['id'])

    # Processando as ofertas
    print("Processing to sent...")
    offers = sellerApi.process_add(offers)

    # Uploading a atualização dos dados para o site
    print("Updating the website...")
    upload_to_site()

    # Waiting for 1 minute to upload to Google
    print("Waiting for 2 minute to upload to Google...")
    time.sleep(120)

    # Enviando para o Shopping
    insert_batch.do(offers)
    def save_published_id(self, published_offer_list):
        print( "Salving Ids")
        
        # Porcessamentos por categoria
        for category in categories:
            print("\t{0}".format( category[ 'name' ] ))

            # Pega a lista de ofertas salva localmente
            local_offers = IOUtil.json_to_dic( 'offers.json', category[ 'id' ] )
            count_remove = 0

            # Percorre todas as ofertas locais 
            for local_offer in tqdm( reversed( local_offers ) ):
                # Buscando por link - a ofertas local tem de está na lista publicada - a menos que foi recusada
                published_offer = self.find_offer(local_offer, published_offer_list, field='link')
                
                # Se a não está publicada, em teoria é porque foi recusada e deve sair da base local
                if published_offer is None:
                    
                    # Deletando a oferta localmente
                    self.process_delete( [local_offer] )
                    local_offers.remove( local_offer )
                    count_remove += 1
                
                else:
                    local_offer['published_id'] = published_offer['id']

            # Salvando as atualizações
            print("Amount of removed offers:", count_remove)
            IOUtil.dic_to_json('offers.json', category[ 'id' ], local_offers)
    def fill_gtin(self, offers, category):
        dic_gtin = IOUtil.json_to_dic('gtin.json', category )
        print( "Requesting GTIN by offer...")

        # Função que busca e preenche cada GTIN    
        def local_request_gtin(offer, dic_gtin):
            # Verifica se tem o GTIN armazendo locamente para aquele produto
            if offer['id'] in dic_gtin.keys():
                # Armazena o GTIN
                gtin = dic_gtin[ offer['id'] ]
            else:
                # Tenta obter o GTIN na Web
                gtin = request_gtin( offer['names'], offer['brand'] )
                
                # Verifica se GTIN foi encontrado
                if gtin is None: 
                    # Tenta pegar o GTIN de outras ofertas do mesmo produto
                    product_id = offer['id'].split('_')[0]
                    
                    # Procura por ofertas do mesmo produto
                    offer_id = None
                    for key in dic_gtin.keys():
                        if product_id in key:
                            offer_id = key
                            break 
                    
                    # Verifica se foi encontrado
                    if offer_id is not None:
                        # Pega o GTIN da oferta
                        gtin = dic_gtin[ offer_id ]
                        
            if gtin is not None:
                offer['gtin'] = gtin
            
            return offer
        
        # Requerindo o GTIN - paralelizado
        nc = mp.cpu_count()
        offers = Parallel(n_jobs=nc)(delayed(local_request_gtin) (offer, dic_gtin) for offer in tqdm(offers))
        
        offers_without_gtin = []
        for offer in reversed( offers ):
            # Armazenando o GTIN
            if 'gtin' in offer.keys():
                # Armazena o GTIN na base local para uso futuro
                dic_gtin[ offer['id'] ] = offer['gtin']
            else:
                # Armazena a oferta sem GTIN para busca manual
                offers_without_gtin.append( offer )
                # Remove a oferta para não ser publicada
                offers.remove( offer )

        # Atualizando a lista de GTINs
        IOUtil.dic_to_json( 'gtin.json', category, dic_gtin)
        # IOUtil.dic_to_json( 'offers_without_gtin.json', category, offers_without_gtin)

        print("Amount of offers without GTIN: ", len(offers_without_gtin))
        return offers
Beispiel #4
0
def main(sellerApi, category):    
    offers = IOUtil.json_to_dic( 'to_update.json', category['id'] )

    if len(offers) == 0:
        print( "No offer to update.")
        return

    sellerApi.process_delete( offers )
    offers = sellerApi.process_add( offers )
    
    print("Updating offers....")
    update.do( offers )
def main(category):
    offers = IOUtil.json_to_dic('to_delete.json', category['id'])

    if len(offers) == 0:
        print("No offer to delete.")
        return

    # Uploading a atualização dos dados para o site
    print("Updating the website...")
    upload_to_site()

    print("Deleting {0} offers...".format(len(offers)))
    delete_batch.do(offers)
    def get_offers(self, category):
        print("Searching Offers...")

        offers = []
        params = ["filters={filters}", "page={page}"]
        url = self._get_url('product/_category/{cat}', size=100, request_params=params)
        
        dict_brands = IOUtil.json_to_dic('brands.json', None )

        print("\tGetting Offers from Category: ", category['name'])
        actual_len = len(offers)
        
        brands = dict_brands[ str(category['id']) ]
        print("\tLooking in {0} Brands.".format(len(brands)))

        def __product_offers(id, brand):
            # Getting offers
            offers_temp = self.get_offers_by_product_id(id)

            # Filling Brand
            for offer in offers_temp:
                offer['brand'] = brand

            return offers_temp

        # Loop por marcas desta categorias
        n_brands = len(brands)
        for i in range( n_brands ):
            brand = brands[ i ]
            
            print("\t\tBrand[{0}/{1}]: {2}".format(i, n_brands, brand['name']))
            print( "\t\tGetting products ids...")
            
            url_cat = url.format(cat=category[ 'id' ], filters=brand['id'], page="{page}")
            products_id = self.get_products_id(url_cat, category)

            # Loop pelos produtos daquela categoria e daquela marca
            print( "\t\tGetting offers from products ids...")
            
            nc = mp.cpu_count()
            list_list_offers = Parallel(n_jobs=nc)(delayed(__product_offers) (id, brand['name']) for id in tqdm(products_id) )

            for list_offers in list_list_offers:
                offers.extend( list_offers )
            
        print("\tAumont of '{0}' found: {1}.".format( category['name'], len(offers) - actual_len))
        print("\tAll found offers: {0}.\n".format(len(offers)))

        return offers
    def process_offers(self, new_offer_list, category):
        print("Processing the offers...")
       
        # Carregando as ofertas por categoria e criando os vetores
        local_offer_list = IOUtil.json_to_dic( 'offers.json', category[ 'id' ] )
        offer_to_add, offer_to_delete, offer_to_update = [], [], []
        
        print("\tStep 1/2")
        # Produtos que serão removidos
        for local_offer in tqdm( reversed(local_offer_list) ):
            # Se a oferta local não estiver mais disponivel, ela deve ser removida
            if self.find_offer(local_offer, new_offer_list) is None:
                # Verifica se a oferta já havia sido publicada
                if 'published_id' in local_offer.keys():
                    # Adicionando para deletar a publicação
                    offer_to_delete.append( local_offer['published_id'] )
                # Removendo a oferta da base local
                local_offer_list.remove( local_offer )
        
        print("\tStep 2/2")
        # Produtos a serem inseridos e atualizados
        for new_offer in tqdm( new_offer_list ):
            # Buscando o produto na lista de publicados
            published_offer = self.find_offer(new_offer, local_offer_list)
            # Não tem esse produto publicado, então ele será publicado e salvo na base local
            if published_offer is None:
                offer_to_add.append( new_offer )
                local_offer_list.append( new_offer )
            
            # Tem o produto publicado, mas o mesmo possui updates
            elif self.has_updates( published_offer, new_offer ):
                # Removendo a oferta da base local
                local_offer_list.remove( published_offer )
                # Verifica se a oferta possui o id de publicação
                if 'published_id' in published_offer.keys():
                    # Adicionando oferta na lista de atualização
                    new_offer['published_id'] = published_offer['published_id']
                    offer_to_update.append( new_offer )
                # Adicionado a oferta atualizada na base local    
                local_offer_list.append( new_offer )
                
        # Salvando as ofertas locamente
        IOUtil.dic_to_json( 'offers.json', category[ 'id' ], local_offer_list )
        print("offer_to_add: ", len(offer_to_add))

        # Retonas as listas
        return offer_to_add, offer_to_delete, offer_to_update
from joblib import Parallel, delayed
import multiprocessing as mp
from tqdm import tqdm

from site_api import image_folder, site_url, local_folder
from util import download_file

from io_util import IOUtil

import os 

from GTIN import request_gtin
from util import str_utf8


categories = IOUtil.json_to_dic('categories.json', None)

APP_TOKEN = '1547052034937b19ab87d'
SOURCE_ID = '36029361'


class SellerAPI:
    def __init__(self):
        self.env = "api"


    def set_test_env(self):
        self.env = "sandbox-api"


    def set_production_env(self):