Skip to content

Commit

Permalink
SFTP_BASE_URL and sftp.exists fix. #1363
Browse files Browse the repository at this point in the history
  • Loading branch information
Toruitas committed Mar 15, 2024
1 parent 70fa8d9 commit 7b322f7
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion docs/backends/sftp.rst
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ Settings

Absolute path of know host file, if it isn't set ``"~/.ssh/known_hosts"`` will be used.

``base_url``
``base_url`` or ``SFTP_BASE_URL``

Default: Django ``MEDIA_URL`` setting

Expand Down
16 changes: 12 additions & 4 deletions storages/backends/sftpstorage.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def get_default_settings(self):
"gid": setting("SFTP_STORAGE_GID"),
"known_host_file": setting("SFTP_KNOWN_HOST_FILE"),
"root_path": setting("SFTP_STORAGE_ROOT", ""),
"base_url": setting("MEDIA_URL"),
"base_url": setting("SFTP_BASE_URL") or setting("MEDIA_URL"),
}

def _connect(self):
Expand Down Expand Up @@ -118,9 +118,12 @@ def _mkdir(self, path):
"""Create directory, recursing up to create parent dirs if
necessary."""
parent = posixpath.dirname(path)
if not self.exists(parent):

if parent and not self.exists(parent):
self._mkdir(parent)
self.sftp.mkdir(path)

if not self.exists(path):
self.sftp.mkdir(path)

if self._dir_mode is not None:
self.sftp.chmod(path, self._dir_mode)
Expand All @@ -133,6 +136,8 @@ def _save(self, name, content):
if is_seekable(content):
content.seek(0, os.SEEK_SET)
path = self._remote_path(name)

# make parent(s)
dirname = posixpath.dirname(path)
if not self.exists(dirname):
self._mkdir(dirname)
Expand All @@ -153,8 +158,11 @@ def delete(self, name):
pass

def exists(self, name):
if not name:
return True

try:
self.sftp.stat(self._remote_path(name))
self.sftp.stat(name)
return True
except FileNotFoundError:
return False
Expand Down

0 comments on commit 7b322f7

Please sign in to comment.