Scrapy, a fast high-level web crawling & scraping framework for Python.
Fix file store modification timestamps (#8196)
Tayyab Nasire8c708f8d4e9
diff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.pyindex 8e49f52e9..c5f8ef9f9 100644--- a/scrapy/pipelines/files.py+++ b/scrapy/pipelines/files.py@@ -15,6 +15,7 @@ import timeimport warningsfrom collections import defaultdictfrom contextlib import suppress+from datetime import datetime, timezonefrom ftplib import FTPfrom io import BytesIOfrom pathlib import Path@@ -202,7 +203,7 @@ class S3FilesStore:def _onsuccess(boto_key: dict[str, Any]) -> StatInfo:checksum = boto_key["ETag"].strip('"')last_modified = boto_key["LastModified"]- modified_stamp = time.mktime(last_modified.timetuple())+ modified_stamp = last_modified.timestamp()return {"checksum": checksum, "last_modified": modified_stamp}def stat_file(@@ -326,7 +327,7 @@ class GCSFilesStore:def _onsuccess(blob: Any) -> StatInfo:if blob:checksum = base64.b64decode(blob.md5_hash).hex()- last_modified = time.mktime(blob.updated.timetuple())+ last_modified = blob.updated.timestamp()return {"checksum": checksum, "last_modified": last_modified}return {}@@ -420,7 +421,13 @@ class FTPFilesStore:if self.USE_ACTIVE_MODE:ftp.set_pasv(False)file_path = f"{self.basedir}/{path}"- last_modified = float(ftp.voidcmd(f"MDTM {file_path}")[4:].strip())+ modified = ftp.voidcmd(f"MDTM {file_path}")[4:].strip()+ time_format = "%Y%m%d%H%M%S.%f" if "." in modified else "%Y%m%d%H%M%S"+ last_modified = (+ datetime.strptime(modified, time_format)+ .replace(tzinfo=timezone.utc)+ .timestamp()+ )m = hashlib.md5() # noqa: S324ftp.retrbinary(f"RETR {file_path}", m.update)return {"last_modified": last_modified, "checksum": m.hexdigest()}diff --git a/tests/test_pipeline_files.py b/tests/test_pipeline_files.pyindex c1d9874cb..2d08fdde7 100644--- a/tests/test_pipeline_files.py+++ b/tests/test_pipeline_files.py@@ -6,7 +6,7 @@ import randomimport reimport timefrom abc import ABC, abstractmethod-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezonefrom ftplib import FTPfrom io import BytesIOfrom pathlib import Path@@ -953,8 +953,12 @@ class TestS3FilesStore:key = "export.csv"uri = f"s3://{bucket}/{key}"checksum = "3187896a9657a28163abb31667df64c8"- # S3FilesStore needs to be fixed to emit tz-aware datetimes- last_modified = datetime(2019, 12, 1) # noqa: DTZ001+ last_modified = datetime(+ 2019,+ 12,+ 1,+ tzinfo=timezone(timedelta(hours=9, minutes=37)),+ )store = S3FilesStore(uri)from botocore.stub import Stubber # noqa: PLC0415@@ -1110,7 +1114,12 @@ class TestGCSFilesStore:store, bucket, blob = self.build_gcs_files_store()checksum = "cdcda85605e46d0af6110752770dce3c"blob.md5_hash = base64.b64encode(bytes.fromhex(checksum)).decode()- updated = datetime(2019, 12, 1, tzinfo=timezone.utc)+ updated = datetime(+ 2019,+ 12,+ 1,+ tzinfo=timezone(timedelta(hours=9, minutes=37)),+ )blob.updated = updatedbucket.get_blob.return_value = blobstat = await maybe_deferred_to_future(@@ -1119,7 +1128,7 @@ class TestGCSFilesStore:bucket.get_blob.assert_called_once_with("my_prefix/full/filename")assert stat == {"checksum": checksum,- "last_modified": time.mktime(updated.timetuple()),+ "last_modified": updated.timestamp(),}@coroutine_test@@ -1168,6 +1177,7 @@ class TestFTPFileStore:)stat = yield store.stat_file(path, info=DUMMY_SPIDER_INFO)assert "last_modified" in stat+ assert stat["last_modified"] == pytest.approx(time.time(), abs=60)assert "checksum" in statassert stat["checksum"] == "d113d66b2ec7258724a268bd88eef6b6"path = f"{store.basedir}/{path}"@@ -1181,6 +1191,33 @@ class TestFTPFileStore:)assert data == content+ @pytest.mark.parametrize(+ ("response", "expected"),+ [+ ("213 20191201010203", 1575162123.0),+ ("213 20191201010203.123456", 1575162123.123456),+ ],+ )+ @inline_callbacks_test+ def test_stat_timestamp(+ self,+ monkeypatch: pytest.MonkeyPatch,+ response: str,+ expected: float,+ ):+ ftp = MagicMock()+ ftp.__enter__.return_value = ftp+ ftp.voidcmd.return_value = response+ ftp.retrbinary.side_effect = lambda command, callback: callback(b"data")+ monkeypatch.setattr(files, "FTP", lambda: ftp)+ monkeypatch.setattr(FTPFilesStore, "FTP_USERNAME", "anonymous")+ monkeypatch.setattr(FTPFilesStore, "FTP_PASSWORD", "guest")++ store = FTPFilesStore("ftp://example.com:21/")+ stat = yield store.stat_file("full/filename", info=DUMMY_SPIDER_INFO)++ assert stat["last_modified"] == expected+@inline_callbacks_testdef test_persist_active_mode(self, monkeypatch: pytest.MonkeyPatch):data = b"active mode"