Skip to content

Instantly share code, notes, and snippets.

@lopezezequiel
Last active December 29, 2015 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lopezezequiel/110a6fc20d1e9b6fcd8b to your computer and use it in GitHub Desktop.
Save lopezezequiel/110a6fc20d1e9b6fcd8b to your computer and use it in GitHub Desktop.
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):
try:
#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
self._ftp.cwd(self._pwd)
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