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

[sftp] Format times to UTC #1420

Merged
merged 1 commit into from
Jul 6, 2024
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
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
Loading