add send ftp

This commit is contained in:
2025-07-18 15:26:41 +02:00
parent f003ba68ed
commit c23027918c
8 changed files with 182 additions and 20 deletions

69
utils/ftp/elab_send.py Normal file
View File

@@ -0,0 +1,69 @@
import ftplib
from io import BytesIO
import logging
import aiomysql
logger = logging.getLogger(__name__)
async def send_csv_to_customer(cfg: dict, id: int, unit: str, tool: str, csv_data: str, pool: object) -> bool:
"""
Sends elaborated CSV data to a customer via FTP.
Retrieves FTP connection details from the database based on the unit name,
then establishes an FTP connection and uploads the CSV data.
Args:
cfg (dict): Configuration dictionary (not directly used in this function but passed for consistency).
id (int): The ID of the record being processed (used for logging).
unit (str): The name of the unit associated with the data.
tool (str): The name of the tool associated with the data.
csv_data (str): The CSV data as a string to be sent.
pool (object): The database connection pool.
Returns:
bool: True if the CSV data was sent successfully, False otherwise.
"""
query = """
select ftp_addrs, ftp_user, ftp_passwd, ftp_parm, ftp_filename, ftp_target, duedate from units
where name = '%s'";'
"""
async with pool.acquire() as conn:
async with conn.cursor(aiomysql.DictCursor) as cur:
try:
await cur.execute(query, (unit,))
send_ftp_info = await cur.fetchone()
logger.info(f"id {id} - {unit} - {tool}: estratti i dati per invio via ftp")
except Exception as e:
logging.error(f"id {id} - {unit} - {tool} - errore nel query per invio ftp: {e}")
try:
# Converti in bytes
csv_bytes = csv_data.encode('utf-8')
csv_buffer = BytesIO(csv_bytes)
# Connessione FTP
with ftplib.FTP(send_ftp_info["ftp_addrs"]) as ftp:
ftp.login(send_ftp_info["ftp_user"], send_ftp_info["ftp_passwd"])
# Cambia directory
if send_ftp_info["ftp_target"] != "/":
ftp.cwd(send_ftp_info["ftp_target"])
# Invia il file
result = ftp.storbinary(f'STOR {send_ftp_info["ftp_filename"]}', csv_buffer)
if result.startswith('226'):
logging.info(f"File {send_ftp_info["ftp_filename"]} inviato con successo")
return True
else:
logging.error(f"Errore nell'invio: {result}")
return False
except ftplib.all_errors as e:
logging.error(f"Errore FTP: {e}")
return False
except Exception as e:
logging.error(f"Errore generico: {e}")
return False
finally:
csv_buffer.close()