MacOS_Parsers/APIlocalhost/Отправляет все json из этой папки на апи.py
2025-11-20 16:51:22 +03:00

72 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
import json
import requests
import time
from datetime import datetime
# === Настройки ===
API_URL = "http://172.25.4.101:3005/parser/data"
FOLDER = os.path.dirname(os.path.abspath(__file__)) # папка, где лежит скрипт
LOG_FILE = os.path.join(FOLDER, "send_log.txt")
RETRIES = 3 # количество попыток при ошибке
TIMEOUT = 60 # секунд ожидания ответа от API
DELAY_BETWEEN = 1 # пауза между файлами (сек.)
def log(message):
"""Пишет строку в лог и в консоль"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
line = f"[{timestamp}] {message}"
print(line)
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(line + "\n")
def send_json(file_path):
"""Отправка одного JSON-файла"""
file_name = os.path.basename(file_path)
try:
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
log(f"❌ Ошибка чтения {file_name}: {e}")
return False
for attempt in range(1, RETRIES + 1):
try:
response = requests.post(API_URL, json=data, timeout=TIMEOUT)
if response.status_code == 200:
log(f"✅ [{attempt}/{RETRIES}] Успешно отправлен {file_name}")
return True
else:
log(f"⚠️ [{attempt}/{RETRIES}] Ошибка {response.status_code} при отправке {file_name}: {response.text}")
except requests.exceptions.RequestException as e:
log(f"🚫 [{attempt}/{RETRIES}] Ошибка соединения при отправке {file_name}: {e}")
if attempt < RETRIES:
time.sleep(3) # пауза между повторами
log(f"Не удалось отправить {file_name} после {RETRIES} попыток.")
return False
def main():
log("🚀 Начало отправки JSON-файлов...")
json_files = [f for f in os.listdir(FOLDER) if f.lower().endswith(".json")]
if not json_files:
log("В текущей папке нет JSON-файлов.")
return
log(f"📦 Найдено {len(json_files)} JSON-файлов для отправки.")
success_count = 0
for i, file_name in enumerate(json_files, start=1):
file_path = os.path.join(FOLDER, file_name)
log(f"➡️ [{i}/{len(json_files)}] Отправка {file_name} ...")
if send_json(file_path):
success_count += 1
time.sleep(DELAY_BETWEEN)
log(f"🏁 Отправка завершена. Успешно: {success_count}/{len(json_files)}")
if __name__ == "__main__":
main()