Skip to content

Instantly share code, notes, and snippets.

Last active December 29, 2015 19:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Keep alive your FTP connections
from ftplib import FTP
import socket
class AliveFTP:
It is a wrapper for ftplib that connects automatically if the
connection is lost. It is connecting the first time a command is
executed(lazy connection). If the command fails, it reconnects and
runs again
def __init__(self, *args,**kwargs):
#Save the connection parameters
self._args = args
self._kwargs = kwargs
def __getattr__(self, name):
if not hasattr(self, '_ftp'):
self._ftp = FTP(*self._args, **self._kwargs)
self._pwd = self._ftp.pwd()
def fn(*args,**kwargs):
#Tries to call the function
val = getattr(self._ftp, name)(*args,**kwargs)
#But if the connection was lost, it is created a new
except socket.error:
self._ftp = FTP(*self._args, **self._kwargs)
#Before running any command, return to the previous path
val = getattr(self._ftp, name)(*args,**kwargs)
#Save new path
self._pwd = self._ftp.pwd()
return val
return fn
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment