Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

call SFTPStorage._connect if ssh connection have been closed #564

Merged
merged 1 commit into from
Aug 26, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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