From 7b322f7a62c9541697ff643ae9bca2e7a37ac45a Mon Sep 17 00:00:00 2001 From: Stuart Leitch Date: Fri, 15 Mar 2024 10:10:14 +0000 Subject: [PATCH] SFTP_BASE_URL and sftp.exists fix. #1363 --- docs/backends/sftp.rst | 2 +- storages/backends/sftpstorage.py | 16 ++++++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/docs/backends/sftp.rst b/docs/backends/sftp.rst index 4de207df..159d8a10 100644 --- a/docs/backends/sftp.rst +++ b/docs/backends/sftp.rst @@ -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 diff --git a/storages/backends/sftpstorage.py b/storages/backends/sftpstorage.py index a7c9aebb..21a4f094 100644 --- a/storages/backends/sftpstorage.py +++ b/storages/backends/sftpstorage.py @@ -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): @@ -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) @@ -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) @@ -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