Introduction
I have written a Python class which uses the module ftplib
. In this class I have created a private
method called __connect()
. Its goal is try to connect to a FTP Server.
Trying the connection could be raised many type of Exception. I have emulated some of these kind of errors:
- a time out error
- a
Connection refused
error because the host (that is reachable) doesn't run a FTP Server
My code
The code of my class is store in the module ftp_connect.py
, and the code inside this module is the following:
import ftplib
CONNECTION_TIMEOUT = 10
class FTPExport:
def __init__(self, server_address, username, password):
self.__server_address = server_address
self.__username = username
self.__password = password
self.__ftpserver = None
def __connect(self):
try:
if self.__server_address == None or self.__server_address == "":
return "Server address error"
self.__ftpserver = ftplib.FTP(self.__server_address, timeout=CONNECTION_TIMEOUT)
return "OK"
except ConnectionRefusedError as ex:
return ex.args[1]
except BaseException as ex:
if len(ex.args) > 0:
if ex.args[0] == 'timed out':
return "Connection timed out"
return "Connection error"
else:
return "Connection error"
if __name__ == '__main__':
# Connection timed out (the address 191.168.127.1 is not reachable on my network)
ftp_export = FTPExport("191.168.127.1", "frank", "123456")
print(ftp_export._FTPExport__connect())
My question is relative to the Timed out error. If you see my code (method __connect()
) I have caught the Exception raised by an occurred Timed Out by the following snippet of code:
try:
...
except BaseException as ex:
if len(ex.args) > 0:
if ex.args[0] == 'timed out':
return "Connection timed out"
...
In the previous code I do:
- catch the
BaseException
because the exception raised when occurs a Timed Out hasBaseException
as superclass - check the content of
args[0]
and if it is equal totimed out
I'm sure that it is occurred a Time Out
How to cause a time out: valid IP address but not reachable
To test my code, make sure that the address 191.168.127.1
is not reachable in your network, and use the following command line:
> python3 ftp_connect.py
If you wait at least 10 seconds you obtain the following output:
Connection timed out
My question
Is it possible to catch the Exception raised by the __init__
method of the class ftplib.FTP
when occurs a Timed Out connection in an other way than by the generic BaseException
and by checking the content of args
?