diff --git a/Pedidos_mar.py b/Pedidos_mar.py index f982bb0..8d541a0 100644 --- a/Pedidos_mar.py +++ b/Pedidos_mar.py @@ -52,6 +52,8 @@ DB_CONNECTION_STRING = ( REQUEST_DELAY = 0.5 # Delay em segundos entre requisições para evitar rate limiting TOKEN_REFRESH_INTERVAL = 50 # Renovar token a cada N lojas processadas +FAILED_STORES_MAX_RETRIES = 3 # Número máximo de tentativas para lojas que falharam +FAILED_STORES_RETRY_DELAY = 180 # Tempo de espera (em segundos) antes de tentar novamente lojas que falharam # =============================== # FUNÇÕES AUXILIARES @@ -455,54 +457,93 @@ BASE_HEADERS = { # 4) LOOP POR LOJA # =============================== +def process_stores(stores_to_process, all_data, base_headers, token): + """ + Processa uma lista de lojas e retorna os dados coletados e as lojas que falharam. + """ + failed = [] + processed_count = 0 + + for store in stores_to_process: + print(f"\nProcessando loja {store}... ({processed_count + 1}/{len(stores_to_process)})") + + # Renovar token periodicamente a cada N lojas + if processed_count > 0 and processed_count % TOKEN_REFRESH_INTERVAL == 0: + print(f"\n[TOKEN] Renovação preventiva após {processed_count} lojas...") + new_token = get_new_token() + if new_token: + token = new_token + base_headers["authorization"] = token + base_headers["x-authorization"] = token + + headers = base_headers.copy() + headers["storecode"] = store + + # Processar loja com retry e callback para renovar token + store_data, needs_refresh = process_store_with_retry( + store, + headers, + max_retries=3, + retry_delay=5, + token_refresh_callback=get_new_token + ) + + # Se precisou renovar token, atualiza os headers base + if needs_refresh: + new_token = get_new_token() + if new_token: + token = new_token + base_headers["authorization"] = token + base_headers["x-authorization"] = token + + # Adicionar dados da loja ao total + all_data.extend(store_data) + processed_count += 1 + + if len(store_data) == 0: + failed.append(store) + + print(f"Loja {store} processada: {len(store_data)} registros") + + return failed, token + all_data = [] -stores_processed = 0 failed_stores = [] -for store in STORES: - print(f"\nProcessando loja {store}... ({stores_processed + 1}/{len(STORES)})") +# Primeira passagem: processar todas as lojas +failed_stores, TOKEN = process_stores(STORES, all_data, BASE_HEADERS, TOKEN) - # Renovar token periodicamente a cada N lojas - if stores_processed > 0 and stores_processed % TOKEN_REFRESH_INTERVAL == 0: - print(f"\n[TOKEN] Renovação preventiva após {stores_processed} lojas...") - new_token = get_new_token() - if new_token: - TOKEN = new_token - BASE_HEADERS["authorization"] = TOKEN - BASE_HEADERS["x-authorization"] = TOKEN +# Retry das lojas que falharam +retry_round = 0 +while failed_stores and retry_round < FAILED_STORES_MAX_RETRIES: + retry_round += 1 + print(f"\n{'=' * 60}") + print(f"[RETRY {retry_round}/{FAILED_STORES_MAX_RETRIES}] {len(failed_stores)} lojas falharam: {', '.join(failed_stores[:20])}{'...' if len(failed_stores) > 20 else ''}") + print(f"Aguardando {FAILED_STORES_RETRY_DELAY} segundos antes de tentar novamente...") + print(f"{'=' * 60}") + time.sleep(FAILED_STORES_RETRY_DELAY) - headers = BASE_HEADERS.copy() - headers["storecode"] = store + # Renovar token antes de tentar novamente + print(f"\n[TOKEN] Renovando token antes do retry...") + new_token = get_new_token() + if new_token: + TOKEN = new_token + BASE_HEADERS["authorization"] = TOKEN + BASE_HEADERS["x-authorization"] = TOKEN - # Processar loja com retry e callback para renovar token - store_data, needs_refresh = process_store_with_retry( - store, - headers, - max_retries=3, - retry_delay=5, - token_refresh_callback=get_new_token - ) + # Tentar processar as lojas que falharam + stores_to_retry = failed_stores.copy() + failed_stores, TOKEN = process_stores(stores_to_retry, all_data, BASE_HEADERS, TOKEN) - # Se precisou renovar token, atualiza os headers base - if needs_refresh: - new_token = get_new_token() - if new_token: - TOKEN = new_token - BASE_HEADERS["authorization"] = TOKEN - BASE_HEADERS["x-authorization"] = TOKEN + if not failed_stores: + print(f"\n[SUCESSO] Todas as lojas foram processadas com sucesso no retry {retry_round}!") - # Adicionar dados da loja ao total - all_data.extend(store_data) - stores_processed += 1 - - if len(store_data) == 0: - failed_stores.append(store) - - print(f"Loja {store} processada: {len(store_data)} registros") - -# Resumo das lojas que falharam +# Resumo final das lojas que ainda falharam if failed_stores: - print(f"\n[AVISO] {len(failed_stores)} lojas falharam: {', '.join(failed_stores[:20])}{'...' if len(failed_stores) > 20 else ''}") + print(f"\n{'=' * 60}") + print(f"[AVISO FINAL] {len(failed_stores)} lojas falharam após {FAILED_STORES_MAX_RETRIES} tentativas de retry:") + print(f" {', '.join(failed_stores)}") + print(f"{'=' * 60}") # =============================== # 5) SALVAR NO BANCO DE DADOS