add ftp parm from db

This commit is contained in:
2025-07-18 17:25:56 +02:00
parent c23027918c
commit a4079ee089

View File

@@ -1,9 +1,42 @@
import ftplib
from ftplib import FTP, FTP_TLS, all_errors
from io import BytesIO
import logging
import aiomysql
logger = logging.getLogger(__name__)
class FTPConnection:
"""
Manages an FTP or FTP_TLS connection, providing a context manager for automatic disconnection.
"""
def __init__(self, host, port=21, use_tls=False, user='', passwd='',
passive=True, timeout=None, debug=0, context=None):
self.use_tls = use_tls
if use_tls:
self.ftp = FTP_TLS(context=context, timeout=timeout) if context else FTP_TLS(timeout=timeout)
else:
self.ftp = FTP(timeout=timeout)
if debug > 0:
self.ftp.set_debuglevel(debug)
self.ftp.connect(host, port)
self.ftp.login(user, passwd)
self.ftp.set_pasv(passive)
if use_tls:
self.ftp.prot_p()
def __getattr__(self, name):
"""Delega tutti i metodi non definiti all'oggetto FTP sottostante"""
return getattr(self.ftp, name)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.ftp.quit()
async def send_csv_to_customer(cfg: dict, id: int, unit: str, tool: str, csv_data: str, pool: object) -> bool:
"""
@@ -41,9 +74,15 @@ async def send_csv_to_customer(cfg: dict, id: int, unit: str, tool: str, csv_dat
csv_bytes = csv_data.encode('utf-8')
csv_buffer = BytesIO(csv_bytes)
ftp_parms = parse_ftp_parms(send_ftp_info["ftp_parm"])
use_tls = 'ssl_version' in ftp_parms
passive = ftp_parms.get('passive', True)
port = ftp_parms.get('port', 21)
# Connessione FTP
with ftplib.FTP(send_ftp_info["ftp_addrs"]) as ftp:
ftp.login(send_ftp_info["ftp_user"], send_ftp_info["ftp_passwd"])
with FTPConnection(host=send_ftp_info["ftp_addrs"], port=port, use_tls=use_tls, user=send_ftp_info["ftp_user"], passwd=send_ftp_info["ftp_passwd"], passive=passive) as ftp:
# Cambia directory
if send_ftp_info["ftp_target"] != "/":
@@ -59,7 +98,7 @@ async def send_csv_to_customer(cfg: dict, id: int, unit: str, tool: str, csv_dat
logging.error(f"Errore nell'invio: {result}")
return False
except ftplib.all_errors as e:
except all_errors as e:
logging.error(f"Errore FTP: {e}")
return False
except Exception as e:
@@ -67,3 +106,34 @@ async def send_csv_to_customer(cfg: dict, id: int, unit: str, tool: str, csv_dat
return False
finally:
csv_buffer.close()
def parse_ftp_parms(ftp_parms):
"""
Parses a string of FTP parameters into a dictionary.
Args:
ftp_parms (str): A string containing key-value pairs separated by commas,
with keys and values separated by '=>'.
Returns:
dict: A dictionary where keys are parameter names (lowercase) and values are their parsed values.
"""
# Rimuovere spazi e dividere per virgola
pairs = ftp_parms.split(',')
result = {}
for pair in pairs:
if '=>' in pair:
key, value = pair.split('=>', 1)
key = key.strip().lower()
value = value.strip().lower()
# Convertire i valori appropriati
if value.isdigit():
value = int(value)
elif value == '':
value = None
result[key] = value
return result