Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Make media pipeline storages configurable components (#7925)

Adrian3cd50142b58e
diff --git a/docs/topics/media-pipeline.rst b/docs/topics/media-pipeline.rst
index 547443091..ffe1d0eea 100644
--- a/docs/topics/media-pipeline.rst
+++ b/docs/topics/media-pipeline.rst
@@ -318,12 +318,12 @@ policy:
For more information, see `canned ACLs`_ in the Amazon S3 Developer Guide.
To send custom headers with the uploaded files, subclass ``S3FilesStore``
-with a different ``HEADERS`` class attribute, and point the ``s3`` scheme of
-your pipeline to it:
+with a different ``HEADERS`` class attribute, and point the ``s3`` scheme to it
+with :setting:`MEDIA_STORAGES`:
.. code-block:: python
- from scrapy.pipelines.files import FilesPipeline, S3FilesStore
+ from scrapy.pipelines.files import S3FilesStore
class CustomS3FilesStore(S3FilesStore):
@@ -332,9 +332,9 @@ your pipeline to it:
"X-Amz-Storage-Class": "STANDARD_IA",
}
+.. code-block:: python
- class CustomFilesPipeline(FilesPipeline):
- STORE_SCHEMES = FilesPipeline.STORE_SCHEMES | {"s3": CustomS3FilesStore}
+ MEDIA_STORAGES = {"s3": "myproject.storages.CustomS3FilesStore"}
Supported headers are those that the installed botocore version models for
the `PutObject`_ operation; any other header raises :exc:`TypeError`.
@@ -402,6 +402,63 @@ For more information, see `Predefined ACLs`_ in the Google Cloud Platform Develo
.. _Predefined ACLs: https://docs.cloud.google.com/storage/docs/access-control/lists#predefined-acl
+.. _media-pipeline-custom-storage:
+
+Custom storage
+--------------
+
+.. versionadded:: VERSION
+
+.. setting:: MEDIA_STORAGES
+
+The :setting:`MEDIA_STORAGES` setting maps URL schemes to storage classes, so
+that you can support additional schemes or replace a built-in storage:
+
+.. code-block:: python
+
+ MEDIA_STORAGES = {"myscheme": "myproject.storages.MyStorage"}
+ FILES_STORE = "myscheme://example.com/files/"
+
+.. setting:: MEDIA_STORAGES_BASE
+
+It is merged into :setting:`MEDIA_STORAGES_BASE`, which holds the built-in
+storages:
+
+.. code-block:: python
+
+ {
+ "": "scrapy.pipelines.files.FSFilesStore",
+ "file": "scrapy.pipelines.files.FSFilesStore",
+ "ftp": "scrapy.pipelines.files.FTPFilesStore",
+ "gs": "scrapy.pipelines.files.GCSFilesStore",
+ "s3": "scrapy.pipelines.files.S3FilesStore",
+ }
+
+A storage class receives the :setting:`FILES_STORE` or :setting:`IMAGES_STORE`
+value, and must define ``stat_file`` and ``persist_file``:
+
+.. code-block:: python
+
+ class MyStorage:
+ def __init__(self, uri, *, acl=None):
+ self.uri = uri
+ self.acl = acl
+
+ @classmethod
+ def from_crawler(cls, crawler, uri, *, get_setting_name):
+ return cls(uri, acl=crawler.settings[get_setting_name("ACL")])
+
+ def stat_file(self, path, info): ...
+
+ def persist_file(self, path, buf, info, meta=None, headers=None): ...
+
+*get_setting_name* adds the prefix of the pipeline being built to a setting
+name, so that a single storage class can be configured separately for files and
+for images: ``get_setting_name("ACL")`` returns ``"FILES_STORE_ACL"`` for
+:class:`~scrapy.pipelines.files.FilesPipeline` and ``"IMAGES_STORE_ACL"`` for
+:class:`~scrapy.pipelines.images.ImagesPipeline`, and takes :ref:`per-class
+setting names <media-pipeline-class-settings>` into account.
+
Usage example
=============
@@ -456,6 +513,8 @@ For the Images Pipeline, set :setting:`IMAGES_URLS_FIELD` and/or
If you need something more complex and want to override the custom pipeline
behaviour, see :ref:`topics-media-pipeline-override`.
+.. _media-pipeline-class-settings:
+
If you have multiple image pipelines inheriting from :class:`ImagesPipeline`
and you want to have different settings in different pipelines you can set
setting keys preceded with uppercase name of your pipeline class. E.g. if your
diff --git a/scrapy/pipelines/files.py b/scrapy/pipelines/files.py
index 86a6ef8a2..885e1eeb6 100644
--- a/scrapy/pipelines/files.py
+++ b/scrapy/pipelines/files.py
@@ -51,16 +51,17 @@ from scrapy.utils.boto import _get_max_pool_connections, is_botocore_available
from scrapy.utils.defer import deferred_from_coro, ensure_awaitable
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.log import failure_to_exc_info
+from scrapy.utils.misc import load_object
+from scrapy.utils.python import without_none_values
from scrapy.utils.request import referer_str
if TYPE_CHECKING:
- from collections.abc import Awaitable
+ from collections.abc import Awaitable, Callable
from os import PathLike
from twisted.python.failure import Failure
from scrapy.crawler import Crawler
- from scrapy.settings import BaseSettings
logger = logging.getLogger(__name__)
@@ -76,7 +77,7 @@ class StatInfo(TypedDict, total=False):
class FilesStoreProtocol(Protocol):
- def __init__(self, basedir: str): ...
+ def __init__(self, uri: str, /): ...
def persist_file(
self,
@@ -151,17 +152,41 @@ class S3FilesStore:
AWS_REGION_NAME = None
AWS_USE_SSL = None
AWS_VERIFY = None
- # Overridden from settings.AWS_MAX_POOL_CONNECTIONS in
- # FilesPipeline.from_crawler(); None means the botocore default
+ # None means the botocore default
AWS_MAX_POOL_CONNECTIONS: int | None = None
UPLOAD_TIMEOUT: float | None = None
- POLICY = "private" # Overridden from settings.FILES_STORE_S3_ACL in FilesPipeline.from_crawler()
+ POLICY = "private"
HEADERS: ClassVar[dict[str, str]] = {
"Cache-Control": "max-age=172800",
}
- def __init__(self, uri: str):
+ @classmethod
+ def from_crawler(
+ cls, crawler: Crawler, uri: str, *, get_setting_name: Callable[[str], str]
+ ) -> Self:
+ return cls(uri, **cls._get_config(crawler, get_setting_name))
+
+ @staticmethod
+ def _get_config(
+ crawler: Crawler, get_setting_name: Callable[[str], str]
+ ) -> dict[str, Any]:
+ settings = crawler.settings
+ return {
+ "AWS_ACCESS_KEY_ID": settings["AWS_ACCESS_KEY_ID"],
+ "AWS_SECRET_ACCESS_KEY": settings["AWS_SECRET_ACCESS_KEY"],
+ "AWS_SESSION_TOKEN": settings["AWS_SESSION_TOKEN"],
+ "AWS_ENDPOINT_URL": settings["AWS_ENDPOINT_URL"],
+ "AWS_REGION_NAME": settings["AWS_REGION_NAME"],
+ "AWS_USE_SSL": settings["AWS_USE_SSL"],
+ "AWS_VERIFY": settings["AWS_VERIFY"],
+ "AWS_MAX_POOL_CONNECTIONS": _get_max_pool_connections(settings),
+ "POLICY": settings[get_setting_name("S3_ACL")],
+ "UPLOAD_TIMEOUT": settings.getfloat("UPLOAD_TIMEOUT") or None,
+ }
+
+ def __init__(self, uri: str, **config: Any):
+ self.__dict__.update(config)
if not is_botocore_available():
raise NotConfigured("missing botocore library")
import botocore.session # noqa: PLC0415
@@ -276,10 +301,27 @@ class GCSFilesStore:
CACHE_CONTROL = "max-age=172800"
# The bucket's default object ACL will be applied to the object.
- # Overridden from settings.FILES_STORE_GCS_ACL in FilesPipeline.from_crawler().
POLICY = None
- def __init__(self, uri: str):
+ @classmethod
+ def from_crawler(
+ cls, crawler: Crawler, uri: str, *, get_setting_name: Callable[[str], str]
+ ) -> Self:
+ return cls(uri, **cls._get_config(crawler, get_setting_name))
+
+ @staticmethod
+ def _get_config(
+ crawler: Crawler, get_setting_name: Callable[[str], str]
+ ) -> dict[str, Any]:
+ settings = crawler.settings
+ return {
+ "GCS_PROJECT_ID": settings["GCS_PROJECT_ID"],
+ "POLICY": settings[get_setting_name("GCS_ACL")] or None,
+ "UPLOAD_TIMEOUT": settings.getfloat("UPLOAD_TIMEOUT") or None,
+ }
+
+ def __init__(self, uri: str, **config: Any):
+ self.__dict__.update(config)
from google.cloud import storage # noqa: PLC0415
client = storage.Client(project=self.GCS_PROJECT_ID)
@@ -358,7 +400,26 @@ class FTPFilesStore:
USE_ACTIVE_MODE: bool | None = None
UPLOAD_TIMEOUT: float | None = None
- def __init__(self, uri: str):
+ @classmethod
+ def from_crawler(
+ cls, crawler: Crawler, uri: str, *, get_setting_name: Callable[[str], str]
+ ) -> Self:
+ return cls(uri, **cls._get_config(crawler, get_setting_name))
+
+ @staticmethod
+ def _get_config(
+ crawler: Crawler, get_setting_name: Callable[[str], str]
+ ) -> dict[str, Any]:
+ settings = crawler.settings
+ return {
+ "FTP_USERNAME": settings["FTP_USER"],
+ "FTP_PASSWORD": settings["FTP_PASSWORD"],
+ "USE_ACTIVE_MODE": settings.getbool("FEED_STORAGE_FTP_ACTIVE"),
+ "UPLOAD_TIMEOUT": settings.getfloat("UPLOAD_TIMEOUT") or None,
+ }
+
+ def __init__(self, uri: str, **config: Any):
+ self.__dict__.update(config)
if not uri.startswith("ftp://"):
raise ValueError(f"Incorrect URI scheme in {uri}, expected 'ftp'")
u = urlparse(uri)
@@ -424,6 +485,58 @@ class FTPFilesStore:
return deferred_from_coro(run_in_thread(self._stat_file, path))
+_STORE_SCHEMES_DEPRECATION = (
+ "FilesPipeline.STORE_SCHEMES is deprecated, use the MEDIA_STORAGES setting instead."
+)
+_BUILTIN_STORE_SCHEMES: dict[str, type[FilesStoreProtocol]] = {
+ "": FSFilesStore,
+ "file": FSFilesStore,
+ "s3": S3FilesStore,
+ "gs": GCSFilesStore,
+ "ftp": FTPFilesStore,
+}
+
+
+class _DeprecatedStoreSchemes:
+ def __init__(self) -> None:
+ self.value: dict[str, type[FilesStoreProtocol]] = dict(_BUILTIN_STORE_SCHEMES)
+
+ def __get__(
+ self, instance: Any, owner: type
+ ) -> dict[str, type[FilesStoreProtocol]]:
+ warnings.warn(
+ _STORE_SCHEMES_DEPRECATION,
+ category=ScrapyDeprecationWarning,
+ stacklevel=2,
+ )
+ return self.value
+
+
+def _store_scheme_overrides(
+ pipeline: FilesPipeline,
+) -> dict[str, type[FilesStoreProtocol] | None]:
+ """Return the schemes that the ``STORE_SCHEMES`` attribute of *pipeline*
+ adds or replaces, and the built-in schemes that it removes, mapped to
+ ``None``.
+ """
+ owner = next(
+ obj
+ for obj in (pipeline, *type(pipeline).__mro__)
+ if "STORE_SCHEMES" in vars(obj)
+ )
+ schemes = vars(owner)["STORE_SCHEMES"]
+ if isinstance(schemes, _DeprecatedStoreSchemes):
+ schemes = schemes.value
+ overrides: dict[str, type[FilesStoreProtocol] | None] = {
+ scheme: store
+ for scheme, store in schemes.items()
+ if _BUILTIN_STORE_SCHEMES.get(scheme) is not store
+ }
+ for scheme in _BUILTIN_STORE_SCHEMES.keys() - schemes.keys():
+ overrides[scheme] = None
+ return overrides
+
+
class FilesPipeline(MediaPipeline):
"""Pipeline that implements file downloading.
@@ -445,13 +558,10 @@ class FilesPipeline(MediaPipeline):
MEDIA_NAME: str = "file"
EXPIRES: int = 90
- STORE_SCHEMES: ClassVar[dict[str, type[FilesStoreProtocol]]] = {
- "": FSFilesStore,
- "file": FSFilesStore,
- "s3": S3FilesStore,
- "gs": GCSFilesStore,
- "ftp": FTPFilesStore,
- }
+ if TYPE_CHECKING:
+ STORE_SCHEMES: ClassVar[dict[str, type[FilesStoreProtocol]]]
+ else:
+ STORE_SCHEMES = _DeprecatedStoreSchemes()
DEFAULT_FILES_URLS_FIELD: str = "file_urls"
DEFAULT_FILES_RESULT_FIELD: str = "files"
@@ -481,8 +591,21 @@ class FilesPipeline(MediaPipeline):
f"to enable {self.__class__.__name__}."
)
+ super().__init__(crawler=crawler)
+
settings = crawler.settings
cls_name = "FilesPipeline"
+ storages = dict(settings.getwithbase("MEDIA_STORAGES"))
+ overrides = _store_scheme_overrides(self)
+ if overrides:
+ warnings.warn(
+ _STORE_SCHEMES_DEPRECATION,
+ category=ScrapyDeprecationWarning,
+ stacklevel=2,
+ )
+ storages.update(overrides)
+ self._storages: dict[str, Any] = without_none_values(storages)
+ self._legacy_schemes: set[str] = set(overrides)
self.store: FilesStoreProtocol = self._get_store(store_uri)
resolve = functools.partial(
self._key_for_pipe, base_class_name=cls_name, settings=settings
@@ -499,53 +622,37 @@ class FilesPipeline(MediaPipeline):
resolve("FILES_RESULT_FIELD"), self.FILES_RESULT_FIELD
)
- super().__init__(crawler=crawler)
-
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
- settings = crawler.settings
- cls._update_stores(settings)
- store_uri = settings["FILES_STORE"]
- return cls(store_uri, crawler=crawler)
+ return cls(crawler.settings["FILES_STORE"], crawler=crawler)
- @classmethod
- def _update_stores(cls, settings: BaseSettings) -> None:
- upload_timeout: float | None = settings.getfloat("UPLOAD_TIMEOUT") or None
-
- s3store: type[S3FilesStore] = cast(
- "type[S3FilesStore]", cls.STORE_SCHEMES["s3"]
- )
- s3store.AWS_ACCESS_KEY_ID = settings["AWS_ACCESS_KEY_ID"]
- s3store.AWS_SECRET_ACCESS_KEY = settings["AWS_SECRET_ACCESS_KEY"]
- s3store.AWS_SESSION_TOKEN = settings["AWS_SESSION_TOKEN"]
- s3store.AWS_ENDPOINT_URL = settings["AWS_ENDPOINT_URL"]
- s3store.AWS_REGION_NAME = settings["AWS_REGION_NAME"]
- s3store.AWS_USE_SSL = settings["AWS_USE_SSL"]
- s3store.AWS_VERIFY = settings["AWS_VERIFY"]
- s3store.AWS_MAX_POOL_CONNECTIONS = _get_max_pool_connections(settings)
- s3store.POLICY = settings["FILES_STORE_S3_ACL"]
- s3store.UPLOAD_TIMEOUT = upload_timeout
-
- gcs_store: type[GCSFilesStore] = cast(
- "type[GCSFilesStore]", cls.STORE_SCHEMES["gs"]
+ def _get_store_setting_name(self, name: str) -> str:
+ return self._key_for_pipe(
+ f"FILES_STORE_{name}", "FilesPipeline", self.crawler.settings
)
- gcs_store.GCS_PROJECT_ID = settings["GCS_PROJECT_ID"]
- gcs_store.POLICY = settings["FILES_STORE_GCS_ACL"] or None
- gcs_store.UPLOAD_TIMEOUT = upload_timeout
-
- ftp_store: type[FTPFilesStore] = cast(
- "type[FTPFilesStore]", cls.STORE_SCHEMES["ftp"]
- )
- ftp_store.FTP_USERNAME = settings["FTP_USER"]
- ftp_store.FTP_PASSWORD = settings["FTP_PASSWORD"]
- ftp_store.USE_ACTIVE_MODE = settings.getbool("FEED_STORAGE_FTP_ACTIVE")
- ftp_store.UPLOAD_TIMEOUT = upload_timeout
def _get_store(self, uri: str) -> FilesStoreProtocol:
# to support win32 paths like: C:\\some\dir
scheme = "file" if Path(uri).is_absolute() else urlparse(uri).scheme
- store_cls = self.STORE_SCHEMES[scheme]
- return store_cls(uri)
+ store_cls = load_object(self._storages[scheme])
+ if scheme in self._legacy_schemes:
+ # Storages from STORE_SCHEMES get the configuration of the
+ # built-in storage of their scheme as class attributes, and are
+ # built with the URI alone.
+ builtin = _BUILTIN_STORE_SCHEMES.get(scheme)
+ if get_config := getattr(builtin, "_get_config", None):
+ config = get_config(self.crawler, self._get_store_setting_name)
+ for name, value in config.items():
+ setattr(store_cls, name, value)
+ return cast("FilesStoreProtocol", store_cls(uri))
+ if hasattr(store_cls, "from_crawler"):
+ return cast(
+ "FilesStoreProtocol",
+ store_cls.from_crawler(
+ self.crawler, uri, get_setting_name=self._get_store_setting_name
+ ),
+ )
+ return cast("FilesStoreProtocol", store_cls(uri))
def _onsuccess(
self,
diff --git a/scrapy/pipelines/images.py b/scrapy/pipelines/images.py
index 19f6309cc..b745170ba 100644
--- a/scrapy/pipelines/images.py
+++ b/scrapy/pipelines/images.py
@@ -11,14 +11,14 @@ import hashlib
import warnings
from contextlib import suppress
from io import BytesIO
-from typing import TYPE_CHECKING, Any, ClassVar, Self, cast
+from typing import TYPE_CHECKING, Any, ClassVar, Self
from itemadapter import ItemAdapter
from scrapy.exceptions import NotConfigured, ScrapyDeprecationWarning
from scrapy.http import Request, Response
from scrapy.http.request import NO_CALLBACK
-from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStore
+from scrapy.pipelines.files import FilesPipeline
from scrapy.pipelines.media import FileException
from scrapy.utils.defer import ensure_awaitable
@@ -30,7 +30,6 @@ if TYPE_CHECKING:
from scrapy.crawler import Crawler
from scrapy.pipelines.media import FileInfoOrError, MediaPipeline
- from scrapy.settings import BaseSettings
class ImageException(FileException):
@@ -113,10 +112,14 @@ class ImagesPipeline(FilesPipeline):
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
- settings = crawler.settings
- cls._update_stores(settings)
- store_uri = settings["IMAGES_STORE"]
- return cls(store_uri, crawler=crawler)
+ return cls(crawler.settings["IMAGES_STORE"], crawler=crawler)
+
+ def _get_store_setting_name(self, name: str) -> str:
+ return self._key_for_pipe(
+ f"IMAGES_STORE_{name}",
+ "ImagesPipeline",
+ self.crawler.settings,
+ )
async def file_downloaded(
self,
@@ -128,20 +131,6 @@ class ImagesPipeline(FilesPipeline):
) -> str:
return await self.image_downloaded(response, request, info, item=item)
- @classmethod
- def _update_stores(cls, settings: BaseSettings) -> None:
- super()._update_stores(settings)
-
- s3store: type[S3FilesStore] = cast(
- "type[S3FilesStore]", cls.STORE_SCHEMES["s3"]
- )
- s3store.POLICY = settings["IMAGES_STORE_S3_ACL"]
-
- gcs_store: type[GCSFilesStore] = cast(
- "type[GCSFilesStore]", cls.STORE_SCHEMES["gs"]
- )
- gcs_store.POLICY = settings["IMAGES_STORE_GCS_ACL"] or None
-
async def image_downloaded(
self,
response: Response,
diff --git a/scrapy/settings/default_settings.py b/scrapy/settings/default_settings.py
index 18787bd0f..62c2a9ca3 100644
--- a/scrapy/settings/default_settings.py
+++ b/scrapy/settings/default_settings.py
@@ -165,6 +165,8 @@ __all__ = [
"MAIL_TLS",
"MAIL_USER",
"MEDIA_CACHE_SIZE",
+ "MEDIA_STORAGES",
+ "MEDIA_STORAGES_BASE",
"MEMDEBUG_ENABLED",
"MEMUSAGE_CHECK_INTERVAL_SECONDS",
"MEMUSAGE_ENABLED",
@@ -506,6 +508,15 @@ MAIL_TLS = False
MEDIA_CACHE_SIZE = -1
+MEDIA_STORAGES: dict[str, str] = {}
+MEDIA_STORAGES_BASE = {
+ "": "scrapy.pipelines.files.FSFilesStore",
+ "file": "scrapy.pipelines.files.FSFilesStore",
+ "ftp": "scrapy.pipelines.files.FTPFilesStore",
+ "gs": "scrapy.pipelines.files.GCSFilesStore",
+ "s3": "scrapy.pipelines.files.S3FilesStore",
+}
+
MEMDEBUG_ENABLED = False # enable memory debugging
MEMUSAGE_ENABLED = True
diff --git a/tests/test_pipeline_files.py b/tests/test_pipeline_files.py
index 35763a5ff..9c2e66b58 100644
--- a/tests/test_pipeline_files.py
+++ b/tests/test_pipeline_files.py
@@ -5,7 +5,9 @@ import mimetypes
import random
import re
import time
+import warnings
from abc import ABC, abstractmethod
+from collections.abc import Callable
from datetime import datetime, timedelta, timezone
from ftplib import FTP
from io import BytesIO
@@ -833,6 +835,146 @@ class TestFilesPipelineCustomSettings:
assert pipeline.file_path(request) == str(Path("subdir/image01.jpg"))
+class SimpleStore:
+ def __init__(self, uri: str) -> None:
+ self.uri = uri
+
+
+class CrawlerAwareStore:
+ def __init__(self, uri: str, crawler: Crawler, acl_setting: str) -> None:
+ self.uri = uri
+ self.crawler = crawler
+ self.acl_setting = acl_setting
+
+ @classmethod
+ def from_crawler(
+ cls, crawler: Crawler, uri: str, *, get_setting_name: Callable[[str], str]
+ ) -> "CrawlerAwareStore":
+ return cls(uri, crawler, get_setting_name("S3_ACL"))
+
+
+class TestMediaStorages:
+ def test_custom_scheme(self, tmp_path: Path) -> None:
+ crawler = get_crawler(
+ None,
+ {
+ "FILES_STORE": "mystore://example.com/",
+ "MEDIA_STORAGES": {
+ "mystore": "tests.test_pipeline_files.CrawlerAwareStore"
+ },
+ },
+ )
+ store = build_from_crawler(FilesPipeline, crawler).store
+ assert isinstance(store, CrawlerAwareStore)
+ assert store.uri == "mystore://example.com/"
+ assert store.crawler is crawler
+ assert store.acl_setting == "FILES_STORE_S3_ACL"
+
+ def test_custom_scheme_without_from_crawler(self, tmp_path: Path) -> None:
+ crawler = get_crawler(
+ None,
+ {
+ "FILES_STORE": "mystore://example.com/",
+ "MEDIA_STORAGES": {"mystore": "tests.test_pipeline_files.SimpleStore"},
+ },
+ )
+ store = build_from_crawler(FilesPipeline, crawler).store
+ assert isinstance(store, SimpleStore)
+ assert store.uri == "mystore://example.com/"
+
+ def test_override_builtin_scheme(self, tmp_path: Path) -> None:
+ crawler = get_crawler(
+ None,
+ {
+ "FILES_STORE": str(tmp_path),
+ "MEDIA_STORAGES": {"file": "tests.test_pipeline_files.SimpleStore"},
+ },
+ )
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", ScrapyDeprecationWarning)
+ pipeline = build_from_crawler(FilesPipeline, crawler)
+ assert isinstance(pipeline.store, SimpleStore)
+
+ def test_store_schemes_read_deprecated(self) -> None:
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ assert FilesPipeline.STORE_SCHEMES["s3"] is S3FilesStore
+
+ def test_store_schemes_extended_deprecated(self, tmp_path: Path) -> None:
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+
+ class DeprecatedPipeline(FilesPipeline):
+ STORE_SCHEMES = {**FilesPipeline.STORE_SCHEMES, "file": SimpleStore} # type: ignore[dict-item]
+
+ crawler = get_crawler(None, {"FILES_STORE": str(tmp_path)})
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ store = build_from_crawler(DeprecatedPipeline, crawler).store
+ assert isinstance(store, SimpleStore)
+
+ def test_store_schemes_replaced_deprecated(self, tmp_path: Path) -> None:
+ class DeprecatedPipeline(FilesPipeline):
+ STORE_SCHEMES = {"file": SimpleStore} # type: ignore[dict-item]
+
+ crawler = get_crawler(None, {"FILES_STORE": str(tmp_path)})
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ store = build_from_crawler(DeprecatedPipeline, crawler).store
+ assert isinstance(store, SimpleStore)
+
+ def test_store_schemes_mutated_deprecated(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ schemes = FilesPipeline.STORE_SCHEMES
+ monkeypatch.setitem(schemes, "file", SimpleStore)
+ crawler = get_crawler(None, {"FILES_STORE": str(tmp_path)})
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ store = build_from_crawler(FilesPipeline, crawler).store
+ assert isinstance(store, SimpleStore)
+
+ def test_store_schemes_instance_deprecated(self, tmp_path: Path) -> None:
+ class DeprecatedPipeline(FilesPipeline):
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ self.STORE_SCHEMES = {"file": SimpleStore} # type: ignore[dict-item,misc]
+ super().__init__(*args, **kwargs)
+
+ crawler = get_crawler(None, {"FILES_STORE": str(tmp_path)})
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ store = build_from_crawler(DeprecatedPipeline, crawler).store
+ assert isinstance(store, SimpleStore)
+
+ def test_store_schemes_subclass_with_uri_only_init(self) -> None:
+ class LegacyFTPFilesStore(FTPFilesStore):
+ def __init__(self, uri: str) -> None: # pylint: disable=useless-parent-delegation
+ super().__init__(uri)
+
+ class DeprecatedPipeline(FilesPipeline):
+ STORE_SCHEMES = {"ftp": LegacyFTPFilesStore}
+
+ crawler = get_crawler(
+ None,
+ {
+ "FILES_STORE": "ftp://example.com:21/files",
+ "FTP_USER": "user",
+ "FTP_PASSWORD": "password",
+ },
+ )
+ with pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"):
+ store = build_from_crawler(DeprecatedPipeline, crawler).store
+ assert isinstance(store, LegacyFTPFilesStore)
+ assert store.username == "user"
+ assert store.password == "password"
+
+ def test_store_schemes_removed(self) -> None:
+ class DeprecatedPipeline(FilesPipeline):
+ STORE_SCHEMES = {"file": FSFilesStore}
+
+ crawler = get_crawler(None, {"FILES_STORE": "ftp://example.com:21/files"})
+ with (
+ pytest.warns(ScrapyDeprecationWarning, match="STORE_SCHEMES"),
+ pytest.raises(KeyError, match="ftp"),
+ ):
+ build_from_crawler(DeprecatedPipeline, crawler)
+
+
class TestFSFilesStore:
def test_constructor_with_pathlike_object(self, tmp_path: Path) -> None:
assert FSFilesStore(tmp_path).basedir == str(tmp_path)
@@ -1035,10 +1177,7 @@ class TestS3FilesStore:
({"UPLOAD_TIMEOUT": 300}, 300),
],
)
- def test_upload_timeout(
- self, monkeypatch: pytest.MonkeyPatch, settings: dict[str, Any], expected: float
- ) -> None:
- monkeypatch.setattr(S3FilesStore, "UPLOAD_TIMEOUT", None)
+ def test_upload_timeout(self, settings: dict[str, Any], expected: float) -> None:
crawler = get_crawler(
settings_dict={"FILES_STORE": "s3://mybucket/prefix/", **settings}
)
@@ -1057,10 +1196,8 @@ class TestS3FilesStore:
],
)
def test_max_pool_connections(
- self, monkeypatch: pytest.MonkeyPatch, settings: dict[str, Any], expected: int
+ self, settings: dict[str, Any], expected: int
) -> None:
- # restores the value that FilesPipeline.from_crawler() sets on the class
- monkeypatch.setattr(S3FilesStore, "AWS_MAX_POOL_CONNECTIONS", None)
crawler = get_crawler(
settings_dict={"FILES_STORE": "s3://mybucket/prefix/", **settings}
)
@@ -1113,26 +1250,40 @@ class TestGCSFilesStore:
in caplog.text
)
- def test_update_stores(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(GCSFilesStore, "GCS_PROJECT_ID", None)
- monkeypatch.setattr(GCSFilesStore, "POLICY", None)
- monkeypatch.setattr(GCSFilesStore, "UPLOAD_TIMEOUT", None)
+ @pytest.mark.parametrize(
+ ("acl", "policy"),
+ [
+ ("publicRead", "publicRead"),
+ # An empty FILES_STORE_GCS_ACL is normalised to None.
+ ("", None),
+ ],
+ )
+ def test_from_crawler(self, acl: str, policy: str | None) -> None:
+ pytest.importorskip("google.cloud.storage")
- settings = Settings(
- {
+ client_mock, bucket_mock, _ = mock_google_cloud_storage()
+ bucket_mock.test_iam_permissions.return_value = [
+ "storage.objects.get",
+ "storage.objects.create",
+ ]
+ crawler = get_crawler(
+ settings_dict={
"GCS_PROJECT_ID": "my-project",
- "FILES_STORE_GCS_ACL": "publicRead",
+ "FILES_STORE_GCS_ACL": acl,
"UPLOAD_TIMEOUT": 300,
}
)
- FilesPipeline._update_stores(settings)
- assert GCSFilesStore.GCS_PROJECT_ID == "my-project"
- assert GCSFilesStore.POLICY == "publicRead"
- assert GCSFilesStore.UPLOAD_TIMEOUT == 300
-
- # An empty FILES_STORE_GCS_ACL is normalised to None.
- settings = Settings({"GCS_PROJECT_ID": "my-project", "FILES_STORE_GCS_ACL": ""})
- FilesPipeline._update_stores(settings)
+ with mock.patch("google.cloud.storage.Client", return_value=client_mock):
+ store = GCSFilesStore.from_crawler(
+ crawler,
+ "gs://my_bucket/my_prefix/",
+ get_setting_name=lambda name: f"FILES_STORE_{name}",
+ )
+
+ assert store.GCS_PROJECT_ID == "my-project"
+ assert store.POLICY == policy
+ assert store.UPLOAD_TIMEOUT == 300
+ assert GCSFilesStore.GCS_PROJECT_ID is None
assert GCSFilesStore.POLICY is None
@coroutine_test
@@ -1240,11 +1391,15 @@ class TestFTPFileStore:
meta = {"foo": "bar"}
path = "full/filename"
with MockFTPServer() as ftp_server:
- # normally set via FilesPipeline.from_crawler()
- FTPFilesStore.FTP_USERNAME = "anonymous"
- FTPFilesStore.FTP_PASSWORD = "guest"
-
- store = FTPFilesStore(ftp_server.url("/"))
+ crawler = get_crawler(
+ settings_dict={
+ "FILES_STORE": ftp_server.url("/"),
+ "FTP_USER": "anonymous",
+ "FTP_PASSWORD": "guest",
+ }
+ )
+ store = build_from_crawler(FilesPipeline, crawler).store
+ assert isinstance(store, FTPFilesStore)
empty_dict = yield store.stat_file(path, info=DUMMY_SPIDER_INFO)
assert empty_dict == {}
yield store.persist_file(
@@ -1285,23 +1440,29 @@ class TestFTPFileStore:
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/")
+ store = FTPFilesStore(
+ "ftp://example.com:21/", FTP_USERNAME="anonymous", FTP_PASSWORD="guest"
+ )
stat = yield store.stat_file("full/filename", info=DUMMY_SPIDER_INFO)
assert stat["last_modified"] == expected
@inline_callbacks_test
- def test_persist_active_mode(self, monkeypatch: pytest.MonkeyPatch):
+ def test_persist_active_mode(self):
data = b"active mode"
path = "full/filename"
- monkeypatch.setattr(FTPFilesStore, "FTP_USERNAME", "anonymous")
- monkeypatch.setattr(FTPFilesStore, "FTP_PASSWORD", "guest")
- monkeypatch.setattr(FTPFilesStore, "USE_ACTIVE_MODE", True)
with MockFTPServer() as ftp_server:
- store = FTPFilesStore(ftp_server.url("/"))
+ crawler = get_crawler(
+ settings_dict={
+ "FILES_STORE": ftp_server.url("/"),
+ "FTP_USER": "anonymous",
+ "FTP_PASSWORD": "guest",
+ "FEED_STORAGE_FTP_ACTIVE": True,
+ }
+ )
+ store = build_from_crawler(FilesPipeline, crawler).store
+ assert isinstance(store, FTPFilesStore)
+ assert store.USE_ACTIVE_MODE
yield store.persist_file(path, BytesIO(data), info=DUMMY_SPIDER_INFO)
stat = yield store.stat_file(path, info=DUMMY_SPIDER_INFO)
assert stat["checksum"] == "ff1575649a39a27c13faa0d37c84bab3"
diff --git a/tests/test_pipeline_images.py b/tests/test_pipeline_images.py
index c8b0fffa3..873d41d26 100644
--- a/tests/test_pipeline_images.py
+++ b/tests/test_pipeline_images.py
@@ -10,6 +10,7 @@ from pathlib import Path
from shutil import rmtree
from tempfile import mkdtemp
from typing import Any
+from unittest import mock
import attr
import pytest
@@ -18,10 +19,12 @@ from itemadapter import ItemAdapter
from scrapy.exceptions import NotConfigured
from scrapy.http import Request, Response
from scrapy.item import Field, Item
-from scrapy.pipelines.files import GCSFilesStore, S3FilesStore
+from scrapy.pipelines.files import FilesPipeline, GCSFilesStore, S3FilesStore
from scrapy.pipelines.images import ImageException, ImagesPipeline
from scrapy.utils.misc import build_from_crawler
from scrapy.utils.test import get_crawler
+from tests.test_pipeline_files import CrawlerAwareStore
+from tests.utils.cloud import mock_google_cloud_storage
from tests.utils.decorators import coroutine_test
from tests.utils.media_pipelines import DUMMY_SPIDER_INFO
@@ -689,43 +692,66 @@ class TestImagesPipelineCustomSettings:
expected_value = settings.get(settings_attr)
assert getattr(pipeline_cls, pipe_attr.lower()) == expected_value
- def test_images_store_s3_acl_setting_used(self, tmp_path):
- old_policy = S3FilesStore.POLICY
-
- try:
- crawler = get_crawler(
- None,
- {
- "IMAGES_STORE": tmp_path,
- "IMAGES_STORE_S3_ACL": "public-read",
- "FILES_STORE_S3_ACL": "private",
+ def test_media_storages_setting_name(self):
+ crawler = get_crawler(
+ None,
+ {
+ "IMAGES_STORE": "mystore://example.com/",
+ "MEDIA_STORAGES": {
+ "mystore": "tests.test_pipeline_files.CrawlerAwareStore"
},
- )
-
- build_from_crawler(ImagesPipeline, crawler)
+ },
+ )
+ store = build_from_crawler(ImagesPipeline, crawler).store
+ assert isinstance(store, CrawlerAwareStore)
+ assert store.acl_setting == "IMAGES_STORE_S3_ACL"
- assert S3FilesStore.POLICY == "public-read"
- finally:
- S3FilesStore.POLICY = old_policy
+ @pytest.mark.requires_botocore
+ def test_images_store_s3_acl_setting_used(self):
+ crawler = get_crawler(
+ None,
+ {
+ "FILES_STORE": "s3://bucket/files/",
+ "IMAGES_STORE": "s3://bucket/images/",
+ "FILES_STORE_S3_ACL": "private",
+ "IMAGES_STORE_S3_ACL": "public-read",
+ },
+ )
- def test_images_store_gcs_acl_setting_used(self, tmp_path):
- old_policy = GCSFilesStore.POLICY
+ files_store = build_from_crawler(FilesPipeline, crawler).store
+ images_store = build_from_crawler(ImagesPipeline, crawler).store
+ assert isinstance(files_store, S3FilesStore)
+ assert isinstance(images_store, S3FilesStore)
+ assert files_store.POLICY == "private"
+ assert images_store.POLICY == "public-read"
+ assert S3FilesStore.POLICY == "private"
- try:
- crawler = get_crawler(
- None,
- {
- "IMAGES_STORE": tmp_path,
- "IMAGES_STORE_GCS_ACL": "authenticatedRead",
- "FILES_STORE_GCS_ACL": "",
- },
- )
+ def test_images_store_gcs_acl_setting_used(self):
+ pytest.importorskip("google.cloud.storage")
- build_from_crawler(ImagesPipeline, crawler)
+ client_mock, bucket_mock, _ = mock_google_cloud_storage()
+ bucket_mock.test_iam_permissions.return_value = [
+ "storage.objects.get",
+ "storage.objects.create",
+ ]
+ crawler = get_crawler(
+ None,
+ {
+ "FILES_STORE": "gs://bucket/files/",
+ "IMAGES_STORE": "gs://bucket/images/",
+ "FILES_STORE_GCS_ACL": "",
+ "IMAGES_STORE_GCS_ACL": "authenticatedRead",
+ },
+ )
- assert GCSFilesStore.POLICY == "authenticatedRead"
- finally:
- GCSFilesStore.POLICY = old_policy
+ with mock.patch("google.cloud.storage.Client", return_value=client_mock):
+ files_store = build_from_crawler(FilesPipeline, crawler).store
+ images_store = build_from_crawler(ImagesPipeline, crawler).store
+ assert isinstance(files_store, GCSFilesStore)
+ assert isinstance(images_store, GCSFilesStore)
+ assert files_store.POLICY is None
+ assert images_store.POLICY == "authenticatedRead"
+ assert GCSFilesStore.POLICY is None
def _create_image(format_: str, *a: Any, **kw: Any) -> tuple[Image.Image, io.BytesIO]:
diff --git a/tests/test_settings/__init__.py b/tests/test_settings/__init__.py
index d29b0b091..e94078591 100644
--- a/tests/test_settings/__init__.py
+++ b/tests/test_settings/__init__.py
@@ -29,6 +29,7 @@ NON_COMPONENT_PRIORITY_DICT_BASE_SETTING_NAMES = {
"DOWNLOAD_HANDLERS_BASE",
"FEED_EXPORTERS_BASE",
"FEED_STORAGES_BASE",
+ "MEDIA_STORAGES_BASE",
}