zmieniono print na logging
zmieniono wyjscie cron z pliku na stdout i stderr
This commit is contained in:
2
crontab
2
crontab
@@ -1 +1 @@
|
||||
0 9,13,16 * * * cd /app && /usr/local/bin/python main.py >> /var/log/cron.log 2>&1
|
||||
0 9,13,16 * * * cd /app && /usr/local/bin/python main.py
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import logging
|
||||
import gspread
|
||||
from google.oauth2.service_account import Credentials
|
||||
|
||||
@@ -11,7 +12,7 @@ class GSheetAPI:
|
||||
"""Inicjalizuje klienta API przy tworzeniu obiektu."""
|
||||
creds = Credentials.from_service_account_file(credentials_file, scopes=SCOPES)
|
||||
self.client = gspread.authorize(creds)
|
||||
print("✅ Połączono z Google Sheets API.")
|
||||
logging.info("✅ Połączono z Google Sheets API.")
|
||||
|
||||
def list_sheets(self, doc_name):
|
||||
"""Zwraca listę arkuszy w danym dokumencie."""
|
||||
@@ -32,7 +33,7 @@ class GSheetAPI:
|
||||
try:
|
||||
ws = spreadsheet.worksheet(sheet_name)
|
||||
except gspread.exceptions.WorksheetNotFound:
|
||||
print(f"➕ Tworzę nowy arkusz: {sheet_name}")
|
||||
logging.info(f"➕ Tworzę nowy arkusz: {sheet_name}")
|
||||
ws = spreadsheet.add_worksheet(title=sheet_name, rows=100, cols=10)
|
||||
ws.append_row(["#", "Link", "Nr zamówienia", "Model", "Wykończenie", "Kolor Top", "Kolor Body", "Kolor Neck", "Kolor Head", "Finish K/C", "Finish S"])
|
||||
return ws
|
||||
@@ -43,38 +44,35 @@ class GSheetAPI:
|
||||
których nr zamówienia (kolumna 3) już istnieje.
|
||||
"""
|
||||
if not rows_data:
|
||||
print("ℹ️ Brak danych do dodania.")
|
||||
logging.info("ℹ️ Brak danych do dodania.")
|
||||
return
|
||||
|
||||
ws = self.ensure_worksheet(doc_name, sheet_name)
|
||||
|
||||
# 1. Pobierz wszystkie istniejące numery zamówień w JEDNYM zapytaniu
|
||||
print("🔍 Sprawdzam istniejące numery zamówień w arkuszu docelowym...")
|
||||
logging.info("🔍 Sprawdzam istniejące numery zamówień w arkuszu docelowym...")
|
||||
# existing_orders = set(ws.col_values(3))
|
||||
existing_orders = {str(x).strip() for x in ws.col_values(3)}
|
||||
|
||||
print(f"Znaleziono {len(existing_orders)} istniejących numerów.\n existing_orders: {existing_orders}")
|
||||
logging.debug(f"Znaleziono {len(existing_orders)} istniejących numerów.\n existing_orders: {existing_orders}")
|
||||
|
||||
# 2. Filtruj nowe wiersze, aby znaleźć tylko te unikalne
|
||||
unique_rows_to_add = []
|
||||
for row in rows_data:
|
||||
order_number = str(row[2]).strip()
|
||||
# print(f"order_number: '{order_number}'", end="")
|
||||
if order_number not in existing_orders:
|
||||
# print(f" not in existing_order!", end="")
|
||||
unique_rows_to_add.append(row)
|
||||
# Dodaj nowo dodany numer do seta, aby uniknąć duplikatów w ramach jednej paczki
|
||||
existing_orders.add(order_number)
|
||||
# print(" ")
|
||||
|
||||
# 3. Dodaj wszystkie unikalne wiersze w JEDNYM zapytaniu
|
||||
if unique_rows_to_add:
|
||||
print(f"📝 Dodaję {len(unique_rows_to_add)} nowych unikalnych wierszy do arkusza {sheet_name}...")
|
||||
logging.info(f"📝 Dodaję {len(unique_rows_to_add)} nowych unikalnych wierszy do arkusza {sheet_name}...")
|
||||
ws.append_rows(unique_rows_to_add, value_input_option="USER_ENTERED") # type: ignore
|
||||
print("✅ Zakończono dodawanie.")
|
||||
logging.info("✅ Zakończono dodawanie.")
|
||||
else:
|
||||
print("ℹ️ Nie znaleziono żadnych nowych wierszy do dodania.")
|
||||
logging.info("ℹ️ Nie znaleziono żadnych nowych wierszy do dodania.")
|
||||
|
||||
skipped_count = len(rows_data) - len(unique_rows_to_add)
|
||||
if skipped_count > 0:
|
||||
print(f"⏭️ Pominięto {skipped_count} wierszy, które już istniały w arkuszu.")
|
||||
logging.info(f"⏭️ Pominięto {skipped_count} wierszy, które już istniały w arkuszu.")
|
||||
10
main.py
10
main.py
@@ -1,4 +1,14 @@
|
||||
import logging
|
||||
import sys
|
||||
from gsheet_api import GSheetAPI
|
||||
|
||||
# Configure logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||
stream=sys.stdout,
|
||||
)
|
||||
|
||||
from mayo import MayoSession
|
||||
from config import MAYO_URL, LOGIN, PASSWORD
|
||||
from workflow import select_sheet, get_sheet_data, save_results
|
||||
|
||||
4
mayo.py
4
mayo.py
@@ -1,6 +1,7 @@
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
import re
|
||||
import logging
|
||||
|
||||
class MayoSession:
|
||||
def __init__(self, base_url, login, password, db="1"):
|
||||
@@ -23,7 +24,7 @@ class MayoSession:
|
||||
r = self.session.post(self.login_url, data=self.credentials)
|
||||
if "Zaloguj się" in r.text or "login" in r.url:
|
||||
raise Exception("Nie udało się zalogować do Mayo.")
|
||||
print("✅ Zalogowano poprawnie do systemu Mayo.")
|
||||
logging.info("✅ Zalogowano poprawnie do systemu Mayo.")
|
||||
|
||||
def get_order_info(self, url):
|
||||
"""
|
||||
@@ -62,7 +63,6 @@ class MayoSession:
|
||||
value = None
|
||||
# Wartość jest zazwyczaj pomiędzy myślnikiem a ukośnikiem
|
||||
match = re.search(r'-\s*([^/]+)', text)
|
||||
# print(f"label: {label}, match: {match}, text: {text}")
|
||||
if match:
|
||||
value = match.group(1).strip()
|
||||
color_sections[label] = value
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import logging
|
||||
|
||||
def normalize(text):
|
||||
if not text:
|
||||
@@ -63,20 +64,20 @@ def process_row(row, mayo, counter):
|
||||
if not link:
|
||||
return None
|
||||
|
||||
print(f"\n🔗 Sprawdzam: {link}")
|
||||
logging.info(f"\n🔗 Sprawdzam: {link}")
|
||||
try:
|
||||
info = mayo.get_order_info(link)
|
||||
order_number = info["order_number"]
|
||||
model = info["model"]
|
||||
|
||||
print(f"Nr z arkusza: {nr_zam}")
|
||||
print(f"Nr ze strony: {order_number}")
|
||||
print(f"Model: {model}")
|
||||
logging.info(f"Nr z arkusza: {nr_zam}")
|
||||
logging.info(f"Nr ze strony: {order_number}")
|
||||
logging.info(f"Model: {model}")
|
||||
|
||||
if normalize(order_number) == normalize(nr_zam):
|
||||
print("✅ Numer się zgadza")
|
||||
logging.info("✅ Numer się zgadza")
|
||||
else:
|
||||
print("⚠️ Numer NIE pasuje!")
|
||||
logging.warning("⚠️ Numer NIE pasuje!")
|
||||
|
||||
row_data = [
|
||||
counter,
|
||||
@@ -91,11 +92,11 @@ def process_row(row, mayo, counter):
|
||||
info.get("finish_kc"),
|
||||
info.get("finish_s"),
|
||||
]
|
||||
print(f"raw_data: {row_data}")
|
||||
logging.debug(f"raw_data: {row_data}")
|
||||
return row_data
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Błąd podczas przetwarzania linku {link}: {e}")
|
||||
logging.error(f"❌ Błąd podczas przetwarzania linku {link}: {e}")
|
||||
return None
|
||||
|
||||
def process_all_rows(rows, mayo):
|
||||
|
||||
13
workflow.py
13
workflow.py
@@ -1,27 +1,28 @@
|
||||
import datetime
|
||||
import logging
|
||||
from config import DOC_NAME, RESULT_DOC
|
||||
|
||||
def select_sheet():
|
||||
"""Generates the sheet name based on the current month and year (MM.YYYY)."""
|
||||
now = datetime.datetime.now()
|
||||
sheet_name = now.strftime("%m.%Y")
|
||||
print(f"📄 Automatycznie wybrano arkusz: {sheet_name}")
|
||||
logging.info(f"📄 Automatycznie wybrano arkusz: {sheet_name}")
|
||||
return sheet_name
|
||||
|
||||
def get_sheet_data(gsheet_api, sheet_name):
|
||||
"""Fetches all data from a given sheet."""
|
||||
print(f"📋 Pobieram dane z arkusza: {sheet_name}")
|
||||
logging.info(f"📋 Pobieram dane z arkusza: {sheet_name}")
|
||||
try:
|
||||
return gsheet_api.get_sheet_data(DOC_NAME, sheet_name)
|
||||
except Exception as e:
|
||||
print(f"❌ Błąd podczas pobierania danych z arkusza: {e}")
|
||||
logging.error(f"❌ Błąd podczas pobierania danych z arkusza: {e}")
|
||||
return None
|
||||
|
||||
def save_results(gsheet_api, sheet_name, processed_rows):
|
||||
"""Saves the processed rows to the spreadsheet."""
|
||||
if processed_rows:
|
||||
print(f"\n\n--- Podsumowanie ---")
|
||||
print(f"Zebrano {len(processed_rows)} wierszy do przetworzenia.")
|
||||
logging.info(f"\n\n--- Podsumowanie ---")
|
||||
logging.info(f"Zebrano {len(processed_rows)} wierszy do przetworzenia.")
|
||||
gsheet_api.batch_append_unique_rows(RESULT_DOC, sheet_name, processed_rows)
|
||||
else:
|
||||
print("\nNie zebrano żadnych danych do przetworzenia.")
|
||||
logging.info("\nNie zebrano żadnych danych do przetworzenia.")
|
||||
|
||||
Reference in New Issue
Block a user