Skip to content

Commit

Permalink
fix #563 call SFTPStorage._connect if ssh connection have been closed
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikhail Nacharov authored and jschneier committed Aug 26, 2018
1 parent 822a5a6 commit 0effd3d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
5 changes: 3 additions & 2 deletions storages/backends/sftpstorage.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ def __init__(self, host=None, params=None, interactive=None, file_mode=None,
# for now it's all posix paths. Maybe someday we'll support figuring
# out if the remote host is windows.
self._pathmod = posixpath
self._sftp = None

def _connect(self):
self._ssh = paramiko.SSHClient()
Expand Down Expand Up @@ -79,13 +80,13 @@ def _connect(self):
except Exception as e:
print(e)

if not hasattr(self, '_sftp'):
if self._ssh.get_transport():
self._sftp = self._ssh.open_sftp()

@property
def sftp(self):
"""Lazy SFTP connection"""
if not hasattr(self, '_sftp'):
if not self._sftp or not self._ssh.get_transport().is_active():
self._connect()
return self._sftp

Expand Down
19 changes: 19 additions & 0 deletions tests/test_sftp.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import stat
from datetime import datetime

import paramiko
from django.core.files.base import File
from django.test import TestCase
from django.utils.six import BytesIO
Expand Down Expand Up @@ -133,6 +134,24 @@ def test_url(self):
self.storage._base_url = None
self.storage.url('foo')

@patch('paramiko.transport.Transport', **{
'is_active.side_effect': (True, False)
})
@patch('storages.backends.sftpstorage.SFTPStorage._connect')
def test_sftp(self, connect, transport):
self.assertIsNone(self.storage.sftp)
self.assertTrue(connect.called)
connect.reset_mock()
self.storage._ssh = paramiko.SSHClient()
self.storage._ssh._transport = transport

self.storage._sftp = True
self.assertTrue(self.storage.sftp)
self.assertFalse(connect.called)

self.assertTrue(self.storage.sftp)
self.assertTrue(connect.called)


class SFTPStorageFileTest(TestCase):
def setUp(self):
Expand Down

0 comments on commit 0effd3d

Please sign in to comment.