Skip to content

ftp

ftp

upload_file_ftp

upload_file_ftp(path: Path, credentials: FtpCredentials, dry_run: bool, upload_filename: str) -> None

Upload path to the iMarina SFTP server.

Raises on connection or upload failure instead of swallowing the error, so the caller can tell a failed publish from a successful one. A failure to close the connection afterwards is logged but not raised, since the file has already been delivered by that point.

Source code in source/src/imarina_load_researchers/core/ftp.py
def upload_file_ftp(
    path: Path,
    credentials: FtpCredentials,
    dry_run: bool,
    upload_filename: str,
) -> None:
    """Upload *path* to the iMarina SFTP server.

    Raises on connection or upload failure instead of swallowing the error,
    so the caller can tell a failed publish from a successful one. A failure
    to close the connection afterwards is logged but not raised, since the
    file has already been delivered by that point.
    """
    logger.info("Connecting to FTP server.")
    try:
        serv = paramiko.Transport((credentials.host, credentials.port))
        serv.connect(username=credentials.username, password=credentials.password)
        ftp = paramiko.SFTPClient.from_transport(serv)
    except Exception:
        logger.exception("Failed to connect to FTP server.")
        raise
    if ftp is None:
        raise SftpSessionError
    logger.info("Connected to FTP server.")

    root_files = ftp.listdir()
    logger.trace(f"Files in entry directory of FTP server are: {root_files}")
    if "carga_icolet" in root_files:
        logger.trace(
            f"Files in carga_icolet folder of remote server: {ftp.listdir('carga_icolet')}"
        )

    if dry_run:
        logger.info("Dry run active: Skipping file upload.")
        return

    logger.info("Uploading file.")
    try:
        ftp.put(path, upload_filename)
    except Exception:
        logger.exception("Failed to upload file to FTP server.")
        raise
    logger.info("File uploaded to FTP server.")

    logger.info("Closing connection.")
    try:
        ftp.close()
    except Exception:
        logger.exception("Failed to close FTP connection.")
    else:
        logger.info("Closed connection.")