-
Hi, Im trying to get files from a sftp that allows maximum 15 connection to it. But with the following code I make a connection for every process that uses connect(). And the disconnect function doesn't seem to close the connections, so is there a better way to close the connection or is there a way to reuse it until it's timed out
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
If you want to make sure the SFTP connection is fully closed, you'll probably want to change your disconnect() call to something like: async def disconnect(self):
self.sftp_client.exit()
await self.sftp_client.wait_closed() However, this will only close the SFTP client session and not the underlying SSH connection. If you want to close the connections, you'll need to keep track of async def connect(self):
self.conn = await asyncssh.connect(**self.credentials)
self.sftp_client = await self.conn.start_sftp_client()
async def disconnect(self):
self.sftp_client.exit()
await self.sftp_client.wait_closed()
self.conn.close()
await self.conn.wait_closed() The cleaner way to do this is to use "async with" context handlers which automatically close the SFTP client session and/or connection when the code leaves the scope, such as in my example: async def run_client() -> None:
async with asyncssh.connect('localhost') as conn:
async with conn.start_sftp_client() as sftp:
await sftp.get('example.txt') However, if you want to be able to exit out of a piece of code but keep the connections around for potential reuse later, the context handler approach doesn't really fit and you have to do the closes manually as I've shown above. If you are worried the connection might time out (or otherwise close) on you in some cases, you'll also need to be prepared to get an error back and open a new connection and SFTP client session and re-try the request when that happens. |
Beta Was this translation helpful? Give feedback.
If you want to make sure the SFTP connection is fully closed, you'll probably want to change your disconnect() call to something like:
However, this will only close the SFTP client session and not the underlying SSH connection. If you want to close the connections, you'll need to keep track of
conn
in your connect() call and later close that connection. This might look something like: