2

I'm building a remote time-lapse camera that takes pictures every half hour and sends them via FTP to my server. A Raspberry Pi will control the camera, gather the files and send them over, via a Python script like so:

while true
    captureImages()
    renameFiles(picID) 
    upload() #uploads any files and folders in the selected path
    delete () #deletes the uploaded files from the pi

My question has to do with this upload function (which works ok) and the subsequent delete function

def upload():#sends the file to server
    print ("connecting")
    #ftp connection (server, user,pass)
    ftp = ftplib.FTP('server','user','pass')

    #folder from which to upload
    template_dir = '/home/pi/captures/'

    print ("uploading")
    #iterate through dirs and files 
    for root, dirs, files in os.walk(template_dir, topdown=True):
        relative = root[len(template_dir):].lstrip(os.sep)
       #enters dirs 
        for d in dirs:
            ftp.mkd(os.path.join(relative, d))
        #uploads files
        for f in files:
            ftp.cwd(relative)
            ftp.storbinary('STOR ' + f, open(os.path.join(template_dir, relative, f), 'rb'))
            ftp.cwd('/')

What I need here are two things:

  1. a way to confirm that the files have been uploaded successfully, like a bool 'uploaded(true/false)' to trigger or not the 'remove' function.

  2. a way to skip the upload process and NOT REMOVE files if the connection cannot be established for whatever reason. Like a timeout, a window of 10 seconds in which it tries to establish the connection and if it cannot it skips both 'upload' and 'remove' and therefore stores the files locally and try again at the next iteration of the while loop.

Thank you in advance for your help!

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
mrc
  • 71
  • 1
  • 7

1 Answers1

1

The code will throw on error. So the upload won't happen, if connection fails. And similarly, the delete won't be called, if upload fails.

All you have to do, is to catch any exception within your endless loop, so that it does not break:

while true
    try:
        captureImages()
        renameFiles(picID) 
        upload() #uploads any files and folders in the selected path
        delete () #deletes the uploaded files from the pi
    except:
        print("Error:", sys.exc_info()[0])

Read about Handling exceptions in Python.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992