Scrapy, a fast high-level web crawling & scraping framework for Python.
Use aioboto3 for S3 feed storage when available (#8330)
Adrian32579047288e
diff --git a/conftest.py b/conftest.pyindex 290dfd8a8..c8d300516 100644--- a/conftest.py+++ b/conftest.py@@ -282,6 +282,7 @@ def pytest_runtest_setup(item):"aiobotocore","botocore","boto3",+ "aioboto3","psutil",]diff --git a/pyproject.toml b/pyproject.tomlindex 1000f6f1d..3185dfe98 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -79,7 +79,7 @@ ipython = ["ipython>=8.15.0"]memusage = ["psutil>=5.9.0"]ptpython = ["ptpython>=3.0.23"]robotparser = ["robotexclusionrulesparser>=1.6.2"]-s3 = ["boto3>=1.35.2"]+s3 = ["aioboto3>=9.0.0", "boto3>=1.35.2"]socks = ["python-socks[asyncio]>=2.6.0"]twisted-http2 = ["Twisted[http2]>=21.7.0"]uvloop = [@@ -143,6 +143,7 @@ implicit_reexport = true# usually no type hints[[tool.mypy.overrides]]module = [+ "aioboto3","aiobotocore.*","bpython","brotli",@@ -299,6 +300,7 @@ markers = ["requires_botocore: marks tests that need botocore (but not boto3)","requires_aiobotocore: marks tests that need aiobotocore","requires_boto3: marks tests that need botocore and boto3",+ "requires_aioboto3: marks tests that need aiobotocore and aioboto3","requires_psutil: marks tests that need psutil","requires_mitmproxy: marks tests that need a mitmdump executable","requires_internet: marks tests that need real Internet access",diff --git a/scrapy/extensions/feedexport.py b/scrapy/extensions/feedexport.pyindex 451b47193..55f908153 100644--- a/scrapy/extensions/feedexport.py+++ b/scrapy/extensions/feedexport.py@@ -13,7 +13,7 @@ import reimport sysimport warningsfrom abc import ABC, abstractmethod-from collections.abc import Callable, Iterable+from collections.abc import Callable, Iterable, Iteratorfrom datetime import UTC, datetimefrom pathlib import Path, PureWindowsPathfrom tempfile import NamedTemporaryFile@@ -30,7 +30,7 @@ from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarningfrom scrapy.extensions.postprocessing import PostProcessingManagerfrom scrapy.utils._ftp import ftp_store_filefrom scrapy.utils.asyncio import is_asyncio_available, run_in_thread-from scrapy.utils.boto import _get_max_pool_connections+from scrapy.utils.boto import _get_max_pool_connections, is_aioboto3_availablefrom scrapy.utils.conf import feed_complete_default_values_from_settingsfrom scrapy.utils.defer import (deferred_from_coro,@@ -318,16 +318,19 @@ class S3FeedStorage(BlockingFeedStorage):if upload_timeout is not None:config_kwargs["read_timeout"] = upload_timeout+ self._client_kwargs: dict[str, Any] = {+ "aws_access_key_id": self.access_key,+ "aws_secret_access_key": self.secret_key,+ "aws_session_token": self.session_token,+ "endpoint_url": self.endpoint_url,+ "region_name": self.region_name,+ "config": Config(**config_kwargs),+ }++ # Synchronous boto3 client, used when asyncio support or aioboto3 is not+ # available (its calls are then run in a thread).boto3_session = boto3.session.Session()- self.s3_client = boto3_session.client(- "s3",- aws_access_key_id=self.access_key,- aws_secret_access_key=self.secret_key,- aws_session_token=self.session_token,- endpoint_url=self.endpoint_url,- region_name=self.region_name,- config=Config(**config_kwargs),- )+ self.s3_client = boto3_session.client("s3", **self._client_kwargs)self._mode: str = _get_mode(self, feed_options, "overwrite")@@ -352,16 +355,59 @@ class S3FeedStorage(BlockingFeedStorage):feed_options=feed_options,)- def _store_in_thread(self, file: IO[bytes]) -> None:+ def store(self, file: IO[bytes]) -> Deferred[None]:+ if is_asyncio_available() and is_aioboto3_available():+ return deferred_from_coro(self._store_async(file))+ return super().store(file)++ async def _store_async(self, file: IO[bytes]) -> None:+ import aioboto3 # noqa: PLC0415++ file.seek(0)+ extra_args: dict[str, Any] = {"ACL": self.acl} if self.acl else {}+ session = aioboto3.Session()+ try:+ async with session.client("s3", **self._client_kwargs) as client:+ if self._mode == "create":+ with self._raise_if_exists():+ await client.put_object(+ Bucket=self.bucketname,+ Key=self.keyname,+ Body=file,+ IfNoneMatch="*",+ **extra_args,+ )+ else:+ await client.upload_fileobj(+ Fileobj=file,+ Bucket=self.bucketname,+ Key=self.keyname,+ ExtraArgs=extra_args,+ )+ finally:+ file.close()++ @contextlib.contextmanager+ def _raise_if_exists(self) -> Iterator[None]:from botocore.exceptions import ClientError # noqa: PLC0415+ try:+ yield+ except ClientError as error:+ if error.response.get("Error", {}).get("Code") == "PreconditionFailed":+ raise FileExistsError(+ f"s3://{self.bucketname}/{self.keyname} already exists"+ ) from error+ raise++ def _store_in_thread(self, file: IO[bytes]) -> None:file.seek(0)extra_args: dict[str, Any] = {"ACL": self.acl} if self.acl else {}try:if self._mode == "create":# upload_fileobj() does not allow IfNoneMatch# (https://github.com/boto/boto3/issues/4366).- try:+ with self._raise_if_exists():self.s3_client.put_object(Bucket=self.bucketname,Key=self.keyname,@@ -369,15 +415,6 @@ class S3FeedStorage(BlockingFeedStorage):IfNoneMatch="*",**extra_args,)- except ClientError as error:- if (- error.response.get("Error", {}).get("Code")- == "PreconditionFailed"- ):- raise FileExistsError(- f"s3://{self.bucketname}/{self.keyname} already exists"- ) from error- raiseelif extra_args:self.s3_client.upload_fileobj(Bucket=self.bucketname,diff --git a/scrapy/utils/boto.py b/scrapy/utils/boto.pyindex fa1edf42d..c01006353 100644--- a/scrapy/utils/boto.py+++ b/scrapy/utils/boto.py@@ -17,6 +17,10 @@ def is_botocore_available() -> bool:return find_spec("botocore") is not None+def is_aioboto3_available() -> bool:+ return find_spec("aioboto3") is not None++def _get_max_pool_connections(settings: BaseSettings) -> int:"""Return the maximum number of connections that AWS clients may keep intheir connection pool.diff --git a/tests/test_feedexport_batch.py b/tests/test_feedexport_batch.pyindex 2c6707858..e379788d5 100644--- a/tests/test_feedexport_batch.py+++ b/tests/test_feedexport_batch.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport jsonfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any+from unittest import mockfrom urllib.parse import urljoinimport pytest@@ -415,7 +416,14 @@ class TestBatchDeliveries:@pytest.mark.requires_boto3@coroutine_test- async def test_s3_export(self, mockserver: MockServer) -> None:+ async def test_s3_export(+ self, mockserver: MockServer, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Force the blocking boto3 code path so that the botocore Stubber below+ # intercepts the uploads.+ monkeypatch.setattr(+ "scrapy.extensions.feedexport.is_aioboto3_available", lambda: False+ )bucket = "mybucket"items = [MyItem({"foo": "bar1", "egg": "spam1"}),@@ -478,3 +486,48 @@ class TestBatchDeliveries:assert (crawler.stats.get_value("feedexport/success_count/CustomS3FeedStorage") == 3)++ @pytest.mark.requires_aioboto3+ @pytest.mark.only_asyncio+ @coroutine_test+ async def test_s3_export_async(+ self, mockserver: MockServer, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """One batch per item is uploaded through the aioboto3 code path."""+ import aioboto3 # noqa: PLC0415++ bucket = "mybucket"+ items = [+ MyItem({"foo": "bar1", "egg": "spam1"}),+ MyItem({"foo": "bar2", "egg": "spam2", "baz": "quux2"}),+ MyItem({"foo": "bar3", "baz": "quux3"}),+ ]++ upload_fileobj = mock.AsyncMock()++ def make_client(self, *args, **kwargs):+ client = mock.MagicMock()+ client.upload_fileobj = upload_fileobj+ client_cm = mock.MagicMock()+ client_cm.__aenter__ = mock.AsyncMock(return_value=client)+ client_cm.__aexit__ = mock.AsyncMock(return_value=False)+ return client_cm++ monkeypatch.setattr(aioboto3.Session, "client", make_client)++ key = "export.csv"+ uri = f"s3://{bucket}/{key}/%(batch_id)d.json"+ settings = {+ "AWS_ACCESS_KEY_ID": "access_key",+ "AWS_SECRET_ACCESS_KEY": "secret_key",+ "FEED_EXPORT_BATCH_ITEM_COUNT": 1,+ "FEEDS": {uri: {"format": "json"}},+ }++ crawler = await crawl_items(mockserver, items, settings)++ assert upload_fileobj.await_count == len(items)+ for call in upload_fileobj.await_args_list:+ assert call.kwargs["Bucket"] == bucket+ assert crawler.stats+ assert crawler.stats.get_value("feedexport/success_count/S3FeedStorage") == 3diff --git a/tests/test_feedexport_storages.py b/tests/test_feedexport_storages.pyindex 78e00992c..701925423 100644--- a/tests/test_feedexport_storages.py+++ b/tests/test_feedexport_storages.py@@ -347,7 +347,12 @@ class TestS3FeedStorage:assert storage.secret_key == "uri_secret"@coroutine_test- async def test_store(self):+ async def test_store(self, monkeypatch):+ """The blocking boto3 client is used when asyncio/aioboto3 support is+ not available."""+ monkeypatch.setattr(+ "scrapy.extensions.feedexport.is_aioboto3_available", lambda: False+ )settings = {"AWS_ACCESS_KEY_ID": "access_key","AWS_SECRET_ACCESS_KEY": "secret_key",@@ -540,7 +545,10 @@ class TestS3FeedStorage:assert config.read_timeout == 60@coroutine_test- async def test_store_without_acl(self):+ async def test_store_without_acl(self, monkeypatch):+ monkeypatch.setattr(+ "scrapy.extensions.feedexport.is_aioboto3_available", lambda: False+ )storage = S3FeedStorage("s3://mybucket/export.csv","access_key",@@ -560,7 +568,10 @@ class TestS3FeedStorage:assert acl is None@coroutine_test- async def test_store_with_acl(self):+ async def test_store_with_acl(self, monkeypatch):+ monkeypatch.setattr(+ "scrapy.extensions.feedexport.is_aioboto3_available", lambda: False+ )storage = S3FeedStorage("s3://mybucket/export.csv", "access_key", "secret_key", "custom-acl")@@ -573,6 +584,40 @@ class TestS3FeedStorage:acl = storage.s3_client.upload_fileobj.call_args[1]["ExtraArgs"]["ACL"]assert acl == "custom-acl"+ @pytest.mark.requires_aioboto3+ @pytest.mark.only_asyncio+ @coroutine_test+ async def test_store_async(self, monkeypatch):+ """The genuinely-asynchronous aioboto3 client is used when+ asyncio/aioboto3 support is available."""+ import aioboto3 # noqa: PLC0415++ storage = S3FeedStorage(+ "s3://mybucket/export.csv", "access_key", "secret_key", "custom-acl"+ )++ client = mock.MagicMock()+ client.upload_fileobj = mock.AsyncMock()+ client_cm = mock.MagicMock()+ client_cm.__aenter__ = mock.AsyncMock(return_value=client)+ client_cm.__aexit__ = mock.AsyncMock(return_value=False)++ file = BytesIO(b"test file")+ with mock.patch.object(+ aioboto3.Session, "client", return_value=client_cm+ ) as client_call:+ await maybe_deferred_to_future(storage.store(file))++ client_call.assert_called_once_with("s3", **storage._client_kwargs)+ client.upload_fileobj.assert_awaited_once_with(+ Fileobj=file,+ Bucket="mybucket",+ Key="export.csv",+ ExtraArgs={"ACL": "custom-acl"},+ )+ client_cm.__aexit__.assert_awaited_once()+ assert file.closed+def test_mode_append(self) -> None:with pytest.raises(ValueError, match="S3FeedStorage does not support the 'append' feed mode"@@ -586,9 +631,13 @@ class TestS3FeedStorage:)@coroutine_test- async def test_store_create(self) -> None:+ async def test_store_create(self, monkeypatch: pytest.MonkeyPatch) -> None:from botocore.stub import ANY, Stubber # noqa: PLC0415+ monkeypatch.setattr(+ "scrapy.extensions.feedexport.is_aioboto3_available", lambda: False+ )+storage = S3FeedStorage("s3://mybucket/export.csv","access_key",@@ -619,11 +668,18 @@ class TestS3FeedStorage:)@coroutine_testasync def test_store_create_error(- self, error_code: str, exception: type[Exception] | None+ self,+ error_code: str,+ exception: type[Exception] | None,+ monkeypatch: pytest.MonkeyPatch,) -> None:from botocore.exceptions import ClientError # noqa: PLC0415from botocore.stub import Stubber # noqa: PLC0415+ monkeypatch.setattr(+ "scrapy.extensions.feedexport.is_aioboto3_available", lambda: False+ )+storage = S3FeedStorage("s3://mybucket/export.csv","access_key",@@ -637,6 +693,54 @@ class TestS3FeedStorage:with pytest.raises(exception or ClientError):await maybe_deferred_to_future(stored)+ @pytest.mark.requires_aioboto3+ @pytest.mark.only_asyncio+ @pytest.mark.parametrize(+ ("error_code", "exception"),+ [(None, None), ("PreconditionFailed", FileExistsError), ("AccessDenied", None)],+ )+ @coroutine_test+ async def test_store_create_async(+ self, error_code: str | None, exception: type[Exception] | None+ ) -> None:+ import aioboto3 # noqa: PLC0415+ from botocore.exceptions import ClientError # noqa: PLC0415++ storage = S3FeedStorage(+ "s3://mybucket/export.csv",+ "access_key",+ "secret_key",+ "custom-acl",+ feed_options={"mode": "create"},+ )++ client = mock.MagicMock()+ client.put_object = mock.AsyncMock()+ if error_code:+ client.put_object.side_effect = ClientError(+ {"Error": {"Code": error_code}}, "PutObject"+ )+ client_cm = mock.MagicMock()+ client_cm.__aenter__ = mock.AsyncMock(return_value=client)+ client_cm.__aexit__ = mock.AsyncMock(return_value=False)++ file = BytesIO(b"test file")+ with mock.patch.object(aioboto3.Session, "client", return_value=client_cm):+ if error_code:+ with pytest.raises(exception or ClientError):+ await maybe_deferred_to_future(storage.store(file))+ else:+ await maybe_deferred_to_future(storage.store(file))++ client.put_object.assert_awaited_once_with(+ Bucket="mybucket",+ Key="export.csv",+ Body=file,+ IfNoneMatch="*",+ ACL="custom-acl",+ )+ assert file.closed+class TestGCSFeedStorage:def test_parse_settings(self):diff --git a/tox.ini b/tox.iniindex 0b5218c33..99f9036b1 100644--- a/tox.ini+++ b/tox.ini@@ -184,6 +184,7 @@ deps =Twisted[http2]python-socks[asyncio]siosocks # SOCKS server for tests+ aioboto3aiobotocoreboto3bpython # optional for shell wrapper tests