Last active
December 29, 2015 19:27
-
-
Save lopezezequiel/110a6fc20d1e9b6fcd8b to your computer and use it in GitHub Desktop.
Keep alive your FTP connections
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
ignore |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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