James James
James James

Reputation: 51

Handling disconnects in Python ftplib FTP transfers file upload

How can I handle disconnects in ftplib?

I wrote a Python scrip that I will use in order to upload very big files to an FTP server using ftplib.

My question is: Seeing as upload will probably take a lot of time due to the file's size, what if the internet disconnects in the middle and then reconnects say after 1 minute? How can I handle such issue in the script? Any ideas?

What I thought about is a try except block that keeps checking if internet connection is available. Any ideas?

Thank you

Upvotes: 4

Views: 1707

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202232

A simple implementation for handling of disconnects while uploading with Python ftplib:

finished = False

local_path = "/local/source/path/file.zip"
remote_path = "/remote/desti/path/file.zip"

with open(local_path, 'rb') as f:
    while (not finished):
        try:
            if ftp is None:
                print("Connecting...")
                ftp = FTP(host, user, passwd)

            if f.tell() > 0:
                rest = ftp.size(remote_path)
                print(f"Resuming transfer from {rest}...")
                f.seek(rest)
            else:
                print("Starting from the beginning...")
                rest = None
            ftp.storbinary(f"STOR {remote_path}", f, rest=rest)
            print("Done")
            finished = True
        except Exception as e:
            ftp = None
            sec = 5
            print(f"Transfer failed: {e}, will retry in {sec} seconds...")
            time.sleep(sec)

More fine-grained exception handling is advisable.

Similarly for downloads:
Resume FTP download after timeout

Upvotes: 1

Related Questions