att
This commit is contained in:
parent
db682de691
commit
516cd95d87
198
Extrair_draft.py
Normal file
198
Extrair_draft.py
Normal file
@ -0,0 +1,198 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
|
import requests
|
||||||
|
import json
|
||||||
|
import socket
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
from requests.exceptions import RequestException
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
|
||||||
|
# URL da API
|
||||||
|
url = "https://mar-orders-bff-api.demanda-abastecimento.grupoboticario.digital/api/orderdraft/order-building-data?draftType=SEM"
|
||||||
|
|
||||||
|
# Cabeçalhos da requisição
|
||||||
|
headers = {
|
||||||
|
"accept": "*/*",
|
||||||
|
"accept-language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7",
|
||||||
|
"authorization": "Basic b2NVc2VySW50ZXJuYWw6Nk5RV0BOU2M1anpEUy1oeg==",
|
||||||
|
"content-type": "application/json",
|
||||||
|
"origin": "https://extranet.grupoboticario.com.br",
|
||||||
|
"priority": "u=1, i",
|
||||||
|
"referer": "https://extranet.grupoboticario.com.br/",
|
||||||
|
"sec-ch-ua": '"Not)A;Brand";v="99", "Google Chrome";v="127", "Chromium";v="127"',
|
||||||
|
"sec-ch-ua-mobile": "?0",
|
||||||
|
"sec-ch-ua-platform": '"Windows"',
|
||||||
|
"sec-fetch-dest": "empty",
|
||||||
|
"sec-fetch-mode": "cors",
|
||||||
|
"sec-fetch-site": "cross-site",
|
||||||
|
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Lista de códigos das lojas
|
||||||
|
store_codes = [
|
||||||
|
"12522", "12817", "12818", "12820", "12823", "12824", "12826", "12828", "12829",
|
||||||
|
"12830", "12838", "13427", "14617", "19103", "20005", "20006", "20009", "20056",
|
||||||
|
"20057", "20441", "20858", "20968", "20969", "20970", "20986", "20988", "20989",
|
||||||
|
"20991", "20992", "20993", "20994", "20995", "20996", "20997", "20998", "20999",
|
||||||
|
"21000", "21001", "21068", "21277", "21278", "21296", "21375", "21381", "21383",
|
||||||
|
"21495", "21624", "21647", "22541", "3546", "4560", "5699", "910173", "910291",
|
||||||
|
"21007", "23665", "23712", "23705", "23711", "23704", "23707", "23702", "23703",
|
||||||
|
"23713", "23708", "23706", "23701", "23709","23475","23156","14668", "24253",
|
||||||
|
"24254", "24255", "24258", "24257", "24268", "24269", "24293", "910291", "910173",
|
||||||
|
"23813"
|
||||||
|
]
|
||||||
|
|
||||||
|
def check_internet_connection():
|
||||||
|
try:
|
||||||
|
# Tenta resolver o endereço para verificar a conectividade
|
||||||
|
socket.gethostbyname("google.com")
|
||||||
|
return True
|
||||||
|
except socket.error:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def fetch_data_from_api(store_code, index, total, retry_count=1):
|
||||||
|
attempt = 0
|
||||||
|
while attempt < retry_count:
|
||||||
|
try:
|
||||||
|
# Definindo storeType com base no código da loja
|
||||||
|
if store_code == "21007":
|
||||||
|
store_type = "TQT"
|
||||||
|
elif store_code in ["910173", "910291"]:
|
||||||
|
store_type = "QDB"
|
||||||
|
else:
|
||||||
|
store_type = "BOT"
|
||||||
|
|
||||||
|
# Dados da requisição com o código da loja
|
||||||
|
data = {
|
||||||
|
"storeCode": store_code,
|
||||||
|
"useId": 163165,
|
||||||
|
"storeType": store_type,
|
||||||
|
"generateNew": False
|
||||||
|
}
|
||||||
|
|
||||||
|
# Fazendo a requisição POST
|
||||||
|
response = requests.post(url, headers=headers, json=data)
|
||||||
|
response.raise_for_status() # Levanta um erro para códigos de status HTTP 4xx/5xx
|
||||||
|
|
||||||
|
# Requisição bem-sucedida
|
||||||
|
response_data = response.json()
|
||||||
|
|
||||||
|
# Nome do arquivo com base no código da loja
|
||||||
|
json_filename = f"{store_code}.json"
|
||||||
|
|
||||||
|
# Salva os dados em um arquivo JSON com o nome do código da loja
|
||||||
|
with open(json_filename, "w") as file:
|
||||||
|
json.dump(response_data, file, indent=4)
|
||||||
|
|
||||||
|
print(f"{index}/{total}: Dados recebidos da API para a loja {store_code} e salvos em '{json_filename}'.")
|
||||||
|
|
||||||
|
# Caminho da nova pasta de destino
|
||||||
|
destination_folder = "/home/danielrodrigues/Scripts/Draft/Arquivos/"
|
||||||
|
|
||||||
|
# Cria a pasta de destino se não existir
|
||||||
|
if not os.path.exists(destination_folder):
|
||||||
|
os.makedirs(destination_folder)
|
||||||
|
|
||||||
|
# Caminho completo do novo local do arquivo
|
||||||
|
new_file_path = os.path.join(destination_folder, json_filename)
|
||||||
|
|
||||||
|
# Move o arquivo JSON para a pasta de destino, substituindo se necessário
|
||||||
|
if os.path.exists(new_file_path):
|
||||||
|
os.remove(new_file_path)
|
||||||
|
|
||||||
|
shutil.move(json_filename, new_file_path)
|
||||||
|
print(f"{index}/{total}: Arquivo movido para '{new_file_path}'.")
|
||||||
|
return True # Retorna True para indicar sucesso
|
||||||
|
|
||||||
|
except RequestException as e:
|
||||||
|
print(f"{index}/{total}: Erro na requisição para a loja {store_code}: {e}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"{index}/{total}: Erro inesperado para a loja {store_code}: {e}")
|
||||||
|
|
||||||
|
attempt += 1
|
||||||
|
print(f"{index}/{total}: Tentativa {attempt} de {retry_count} para a loja {store_code}.")
|
||||||
|
time.sleep(5) # Espera antes de tentar novamente
|
||||||
|
|
||||||
|
print(f"{index}/{total}: Falha ao processar a loja {store_code} após {retry_count} tentativas.")
|
||||||
|
return False # Retorna False para indicar falha
|
||||||
|
|
||||||
|
def update_api_status(status):
|
||||||
|
import requests
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
|
||||||
|
# URL do endpoint
|
||||||
|
url = "https://api.grupoginseng.com.br/api/status/1"
|
||||||
|
|
||||||
|
# Definir fuso horário de São Paulo (UTC-3)
|
||||||
|
sao_paulo_offset = timedelta(hours=-3)
|
||||||
|
|
||||||
|
# Gerar data/hora atual no formato YYYY-MM-DD HH:MM:SS com UTC-3
|
||||||
|
current_datetime = datetime.now(timezone(sao_paulo_offset)).strftime("%Y-%m-%d %H:%M:%S")
|
||||||
|
|
||||||
|
# Montar o payload
|
||||||
|
payload = {
|
||||||
|
"STATUS": status,
|
||||||
|
"DATA": current_datetime
|
||||||
|
}
|
||||||
|
|
||||||
|
# Cabeçalhos
|
||||||
|
headers = {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Enviar PUT request
|
||||||
|
response = requests.put(url, json=payload, headers=headers)
|
||||||
|
|
||||||
|
# Mostrar resposta
|
||||||
|
print("Hora enviada:", current_datetime)
|
||||||
|
print("Status Code:", response.status_code)
|
||||||
|
print("Response Body:", response.text)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
if check_internet_connection():
|
||||||
|
failed_stores = []
|
||||||
|
total = len(store_codes)
|
||||||
|
|
||||||
|
# Processa todas as lojas
|
||||||
|
for index, store_code in enumerate(store_codes, start=1):
|
||||||
|
success = fetch_data_from_api(store_code, index, total)
|
||||||
|
if not success:
|
||||||
|
failed_stores.append(store_code)
|
||||||
|
|
||||||
|
# Tenta novamente as lojas que falharam
|
||||||
|
if failed_stores:
|
||||||
|
print("Tentando novamente as lojas que falharam.")
|
||||||
|
retry_count = 1
|
||||||
|
for attempt in range(1, retry_count + 1):
|
||||||
|
retry_failed_stores = []
|
||||||
|
for store_code in failed_stores:
|
||||||
|
index = store_codes.index(store_code) + 1
|
||||||
|
success = fetch_data_from_api(store_code, index, total)
|
||||||
|
if not success:
|
||||||
|
retry_failed_stores.append(store_code)
|
||||||
|
|
||||||
|
failed_stores = retry_failed_stores
|
||||||
|
if not failed_stores:
|
||||||
|
print("Todos os arquivos foram processados com sucesso.")
|
||||||
|
update_api_status("OK")
|
||||||
|
break
|
||||||
|
|
||||||
|
if failed_stores:
|
||||||
|
print(f"Tentativa {attempt} de {retry_count} para as lojas que falharam.")
|
||||||
|
time.sleep(10) # Espera antes de tentar novamente
|
||||||
|
|
||||||
|
# Se ainda houver lojas com falha após todas as tentativas
|
||||||
|
if failed_stores:
|
||||||
|
print(f"Não foi possível processar algumas lojas: {failed_stores}")
|
||||||
|
update_api_status("FAIL")
|
||||||
|
else:
|
||||||
|
print("Todos os arquivos foram processados com sucesso.")
|
||||||
|
update_api_status("OK")
|
||||||
|
else:
|
||||||
|
print("Sem conexão com a internet. Verifique sua conexão e tente novamente.")
|
||||||
|
update_api_status("FAIL")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Loading…
x
Reference in New Issue
Block a user