Skip to content

Instantly share code, notes, and snippets.

@lopezezequiel

lopezezequiel/.gitignore

Last active Dec 29, 2015
Embed
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):
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