@@ -109,32 +109,54 @@ class FTP:
109109 welcome = None
110110 passiveserver = 1
111111 encoding = "latin-1"
112- # Disables https://bugs.python.org/issue43285 security if set to True.
113- trust_server_pasv_ipv4_address = False
112+ # # Disables https://bugs.python.org/issue43285 security if set to True.
113+ # trust_server_pasv_ipv4_address = False
114114
115115 # Initialization method (called by class instantiation).
116116 # Initialize host to localhost, port to standard ftp port
117117 # Optional arguments are host (for connect()),
118118 # and user, passwd, acct (for login())
119119 def __init__ (self , host = '' , user = '' , passwd = '' , acct = '' ,
120- timeout = _GLOBAL_DEFAULT_TIMEOUT ):
120+ timeout = _GLOBAL_DEFAULT_TIMEOUT , source_address = None ):
121+ self .source_address = source_address
122+ # Disables https://bugs.python.org/issue43285 security if set to True.
123+ self .trust_server_pasv_ipv4_address = False
121124 self .timeout = timeout
122125 if host :
123126 self .connect (host )
124127 if user :
125128 self .login (user , passwd , acct )
126129
127- def connect (self , host = '' , port = 0 , timeout = - 999 ):
130+ def __enter__ (self ):
131+ return self
132+
133+ # Context management protocol: try to quit() if active
134+ def __exit__ (self , * args ):
135+ if self .sock is not None :
136+ try :
137+ self .quit ()
138+ except (OSError , EOFError ):
139+ pass
140+ finally :
141+ if self .sock is not None :
142+ self .close ()
143+
144+ def connect (self , host = '' , port = 0 , timeout = - 999 , source_address = None ):
128145 '''Connect to host. Arguments are:
129146 - host: hostname to connect to (string, default previous host)
130147 - port: port to connect to (integer, default previous port)
148+ - timeout: the timeout to set against the ftp socket(s)
149+ - source_address: a 2-tuple (host, port) for the socket to bind
150+ to as its source address before connecting.
131151 '''
132152 if host != '' :
133153 self .host = host
134154 if port > 0 :
135155 self .port = port
136156 if timeout != - 999 :
137157 self .timeout = timeout
158+ if source_address is not None :
159+ self .source_address = source_address
138160 self .sock = socket .create_connection ((self .host , self .port ), self .timeout )
139161 self .af = self .sock .family
140162 self .file = self .sock .makefile ('rb' )
0 commit comments