Skip to content

Commit

Permalink
[sftp] Format times to UTC (#1420)
Browse files Browse the repository at this point in the history
  • Loading branch information
jschneier authored Jul 6, 2024
1 parent ea25226 commit 4cd12e0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
14 changes: 8 additions & 6 deletions storages/backends/sftpstorage.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,16 @@
#
# Modeled on the FTP storage by Rafal Jonca <[email protected]>

import datetime
import getpass
import io
import os
import posixpath
import stat
from datetime import datetime
from urllib.parse import urljoin

import paramiko
from django.core.files.base import File
from django.utils import timezone
from django.utils.deconstruct import deconstructible
from paramiko.util import ClosingContextManager

Expand Down Expand Up @@ -192,17 +191,20 @@ def size(self, name):
remote_path = self._remote_path(name)
return self.sftp.stat(remote_path).st_size

# From Django
def _datetime_from_timestamp(self, ts):
tz = datetime.timezone.utc if setting("USE_TZ") else None
return datetime.datetime.fromtimestamp(ts, tz=tz)

def get_accessed_time(self, name):
remote_path = self._remote_path(name)
utime = self.sftp.stat(remote_path).st_atime
ts = datetime.fromtimestamp(utime)
return timezone.make_aware(ts) if setting("USE_TZ") else ts
return self._datetime_from_timestamp(utime)

def get_modified_time(self, name):
remote_path = self._remote_path(name)
utime = self.sftp.stat(remote_path).st_mtime
ts = datetime.fromtimestamp(utime)
return timezone.make_aware(ts) if setting("USE_TZ") else ts
return self._datetime_from_timestamp(utime)

def url(self, name):
if self._base_url is None:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_sftp.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,17 @@ def test_url(self):
self.storage._base_url = None
self.storage.url("foo")

@patch(
"storages.backends.sftpstorage.SFTPStorage.sftp",
**{
"stat.return_value.st_mtime": 1720287559,
"stat.return_value.st_atime": 1720287559,
},
)
def test_times(self, mock_sftp):
self.storage.get_modified_time("foo")
self.storage.get_accessed_time("foo")

@patch("paramiko.transport.Transport", **{"is_active.side_effect": (True, False)})
@patch("storages.backends.sftpstorage.SFTPStorage._connect")
def test_sftp(self, connect, transport):
Expand Down

0 comments on commit 4cd12e0

Please sign in to comment.