Scrapy, a fast high-level web crawling & scraping framework for Python.
Deprecate some of scrapy.utils (#8135)
Andrey Rakhmatullinf52c4efe1b47
diff --git a/docs/news.rst b/docs/news.rstindex 7482f7358..299358c8f 100644--- a/docs/news.rst+++ b/docs/news.rst@@ -1618,7 +1618,7 @@ Deprecation removals- ``scrapy.utils.versions.scrapy_components_versions()``, deprecated inScrapy 2.13.0, is removed, you can use- :func:`scrapy.utils.versions.get_versions` instead.+ ``scrapy.utils.versions.get_versions()`` instead.(:gh:`7487`)- ``scrapy.downloadermiddlewares.ajaxcrawl.AjaxCrawlMiddleware`` and@@ -3330,7 +3330,7 @@ Deprecations(:gh:`6708`, :gh:`6714`)- ``scrapy.utils.versions.scrapy_components_versions()`` is deprecated, use- :func:`scrapy.utils.versions.get_versions` instead.+ ``scrapy.utils.versions.get_versions()`` instead.(:gh:`6582`)- ``BaseDupeFilter.log()`` is deprecated. It does nothing and shouldn't be@@ -7580,7 +7580,7 @@ Bug fixesare now properly decoded (:gh:`3941`)* A memory-handling and error-handling issue in- :func:`scrapy.utils.ssl.get_temp_key_info` has been fixed (:gh:`3920`)+ ``scrapy.utils.ssl.get_temp_key_info()`` has been fixed (:gh:`3920`)Documentationdiff --git a/scrapy/commands/bench.py b/scrapy/commands/bench.pyindex 0a5b431a2..dbe1dc1da 100644--- a/scrapy/commands/bench.py+++ b/scrapy/commands/bench.py@@ -36,7 +36,7 @@ class Command(ScrapyCommand):class _BenchServer:def __enter__(self) -> None:- pargs = [sys.executable, "-u", "-m", "scrapy.utils.benchserver"]+ pargs = [sys.executable, "-u", "-m", "scrapy.utils._benchserver"]self.proc = subprocess.Popen( # noqa: S603pargs, stdout=subprocess.PIPE, env=get_testenv())diff --git a/scrapy/commands/version.py b/scrapy/commands/version.pyindex 1d1985d4e..840db82ba 100644--- a/scrapy/commands/version.py+++ b/scrapy/commands/version.py@@ -3,7 +3,7 @@ from typing import Any, ClassVarimport scrapyfrom scrapy.commands import ScrapyCommand-from scrapy.utils.versions import get_versions+from scrapy.utils._versions import get_versionsclass Command(ScrapyCommand):diff --git a/scrapy/core/_http2/protocol.py b/scrapy/core/_http2/protocol.pyindex c1cebee41..2a557830e 100644--- a/scrapy/core/_http2/protocol.py+++ b/scrapy/core/_http2/protocol.py@@ -35,8 +35,8 @@ from zope.interface import implementerfrom scrapy.core._http2.stream import Stream, StreamCloseReasonfrom scrapy.exceptions import DownloadTimeoutErrorfrom scrapy.http import Request, Response+from scrapy.utils._ssl import _log_ssl_conn_debug_infofrom scrapy.utils.deprecate import warn_on_deprecated_spider_attribute-from scrapy.utils.ssl import _log_ssl_conn_debug_infoif TYPE_CHECKING:from ipaddress import IPv4Address, IPv6Addressdiff --git a/scrapy/core/downloader/contextfactory.py b/scrapy/core/downloader/contextfactory.pyindex a599a8e03..a098414e3 100644--- a/scrapy/core/downloader/contextfactory.py+++ b/scrapy/core/downloader/contextfactory.py@@ -22,14 +22,14 @@ from scrapy.core.downloader.tls import ()from scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.utils._deps_compat import TWISTED_TLS_NEW_IMPL-from scrapy.utils.deprecate import create_deprecated_class-from scrapy.utils.misc import build_from_crawler, load_object-from scrapy.utils.ssl import (+from scrapy.utils._ssl import (_get_cert_options_version_kwargs,_get_keylog_filename,_get_tls_version_limits,_set_keylog_callback,)+from scrapy.utils.deprecate import create_deprecated_class+from scrapy.utils.misc import build_from_crawler, load_objectif TYPE_CHECKING:from twisted.internet._sslverify import ClientTLSOptionsdiff --git a/scrapy/core/downloader/handlers/_aiohttp.py b/scrapy/core/downloader/handlers/_aiohttp.pyindex 75be971dd..d2cad2b19 100644--- a/scrapy/core/downloader/handlers/_aiohttp.py+++ b/scrapy/core/downloader/handlers/_aiohttp.py@@ -18,7 +18,7 @@ from scrapy.exceptions import (UnsupportedURLSchemeError,)from scrapy.http import Headers-from scrapy.utils.ssl import _log_sslobj_debug_info, _make_ssl_context+from scrapy.utils._ssl import _log_sslobj_debug_info, _make_ssl_contextfrom ._base_streaming import BaseStreamingDownloadHandler, _BaseResponseArgsdiff --git a/scrapy/core/downloader/handlers/_httpx.py b/scrapy/core/downloader/handlers/_httpx.pyindex 8bbffb233..1d138254c 100644--- a/scrapy/core/downloader/handlers/_httpx.py+++ b/scrapy/core/downloader/handlers/_httpx.py@@ -18,12 +18,12 @@ from scrapy.exceptions import ()from scrapy.http import Headersfrom scrapy.utils._download_handlers import NullCookieJar-from scrapy.utils.python import _iter_exc_causes-from scrapy.utils.ssl import (+from scrapy.utils._ssl import (_log_sslobj_debug_info,_make_insecure_ssl_ctx,_make_ssl_context,)+from scrapy.utils.python import _iter_exc_causesfrom ._base_streaming import BaseStreamingDownloadHandler, _BaseResponseArgsdiff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex 4cc7cf944..6b41663df 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -57,11 +57,11 @@ from scrapy.utils._download_handlers import (normalize_bind_address,wrap_twisted_exceptions,)+from scrapy.utils._ssl import _log_ssl_conn_debug_infofrom scrapy.utils.defer import maybe_deferred_to_futurefrom scrapy.utils.deprecate import warn_on_deprecated_spider_attributefrom scrapy.utils.httpobj import urlparse_cachedfrom scrapy.utils.python import to_bytes, to_unicode-from scrapy.utils.ssl import _log_ssl_conn_debug_infofrom scrapy.utils.url import add_http_if_no_schemefrom ._base_http import BaseHttpDownloadHandlerdiff --git a/scrapy/core/scheduler.py b/scrapy/core/scheduler.pyindex a511b0c7b..2194d9845 100644--- a/scrapy/core/scheduler.py+++ b/scrapy/core/scheduler.py@@ -10,7 +10,7 @@ from typing import TYPE_CHECKING, Any, castfrom twisted.internet.defer import Deferred # noqa: TC002from scrapy.spiders import Spider # noqa: TC001-from scrapy.utils.job import job_dir+from scrapy.utils.conf import _job_dirfrom scrapy.utils.misc import build_from_crawler, load_objectif TYPE_CHECKING:@@ -255,7 +255,7 @@ class Scheduler(BaseScheduler):dupefilter_cls = load_object(crawler.settings["DUPEFILTER_CLASS"])return cls(dupefilter=build_from_crawler(dupefilter_cls, crawler),- jobdir=job_dir(crawler.settings),+ jobdir=_job_dir(crawler.settings),dqclass=load_object(crawler.settings["SCHEDULER_DISK_QUEUE"]),mqclass=load_object(crawler.settings["SCHEDULER_MEMORY_QUEUE"]),logunser=crawler.settings.getbool("SCHEDULER_DEBUG"),diff --git a/scrapy/downloadermiddlewares/httpcompression.py b/scrapy/downloadermiddlewares/httpcompression.pyindex 1a354307e..674384a26 100644--- a/scrapy/downloadermiddlewares/httpcompression.py+++ b/scrapy/downloadermiddlewares/httpcompression.py@@ -14,10 +14,10 @@ from scrapy.utils._compression import (_inflate,_unbrotli,_unzstd,+ gunzip,)from scrapy.utils.decorators import _warn_spider_argfrom scrapy.utils.deprecate import warn_on_deprecated_spider_attribute-from scrapy.utils.gz import gunzipif TYPE_CHECKING:# typing.Self requires Python 3.11diff --git a/scrapy/dupefilters.py b/scrapy/dupefilters.pyindex 94ed3b11f..65c69b8a9 100644--- a/scrapy/dupefilters.py+++ b/scrapy/dupefilters.py@@ -6,8 +6,8 @@ from typing import TYPE_CHECKINGfrom warnings import warnfrom scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils.conf import _job_dirfrom scrapy.utils.deprecate import method_is_overridden-from scrapy.utils.job import job_dirfrom scrapy.utils.request import (RequestFingerprinter,RequestFingerprinterProtocol,@@ -132,7 +132,7 @@ class RFPDupeFilter(BaseDupeFilter):def from_crawler(cls, crawler: Crawler) -> Self:debug = crawler.settings.getbool("DUPEFILTER_DEBUG")return cls(- job_dir(crawler.settings),+ _job_dir(crawler.settings),debug,fingerprinter=crawler.request_fingerprinter,)diff --git a/scrapy/extensions/spiderstate.py b/scrapy/extensions/spiderstate.pyindex 7b8756572..3166834dc 100644--- a/scrapy/extensions/spiderstate.py+++ b/scrapy/extensions/spiderstate.py@@ -6,7 +6,7 @@ from typing import TYPE_CHECKINGfrom scrapy import Spider, signalsfrom scrapy.exceptions import NotConfigured-from scrapy.utils.job import job_dir+from scrapy.utils.conf import _job_dirif TYPE_CHECKING:# typing.Self requires Python 3.11@@ -23,7 +23,7 @@ class SpiderState:@classmethoddef from_crawler(cls, crawler: Crawler) -> Self:- jobdir = job_dir(crawler.settings)+ jobdir = _job_dir(crawler.settings)if not jobdir:raise NotConfigureddiff --git a/scrapy/shell.py b/scrapy/shell.pyindex 8f78af571..294b43893 100644--- a/scrapy/shell.py+++ b/scrapy/shell.py@@ -25,8 +25,8 @@ from scrapy.exceptions import IgnoreRequest, ScrapyDeprecationWarningfrom scrapy.http import Request, Responsefrom scrapy.settings import Settingsfrom scrapy.spiders import Spider+from scrapy.utils._shell import DEFAULT_PYTHON_SHELLS, start_python_consolefrom scrapy.utils.conf import get_config-from scrapy.utils.console import DEFAULT_PYTHON_SHELLS, start_python_consolefrom scrapy.utils.datatypes import SequenceExcludefrom scrapy.utils.defer import deferred_f_from_coro_f, maybe_deferred_to_futurefrom scrapy.utils.misc import load_objectdiff --git a/scrapy/spiders/sitemap.py b/scrapy/spiders/sitemap.pyindex 2a80b8d24..92acef9d3 100644--- a/scrapy/spiders/sitemap.py+++ b/scrapy/spiders/sitemap.py@@ -9,8 +9,11 @@ from typing import TYPE_CHECKING, Any, castfrom scrapy.http import Request, Response, XmlResponsefrom scrapy.spiders import Spider-from scrapy.utils._compression import _DecompressionMaxSizeExceeded-from scrapy.utils.gz import gunzip, gzip_magic_number+from scrapy.utils._compression import (+ _DecompressionMaxSizeExceeded,+ gunzip,+ gzip_magic_number,+)from scrapy.utils.sitemap import Sitemap, sitemap_urls_from_robotsif TYPE_CHECKING:diff --git a/scrapy/utils/_benchserver.py b/scrapy/utils/_benchserver.pynew file mode 100644index 000000000..b3d3caab7--- /dev/null+++ b/scrapy/utils/_benchserver.py@@ -0,0 +1,55 @@+import random+from typing import Any+from urllib.parse import urlencode++from twisted.web.resource import Resource+from twisted.web.server import Request, Site+++class Root(Resource):+ isLeaf = True++ def getChild(self, path: str, request: Request) -> Resource:+ return self++ def render(self, request: Request) -> bytes:+ total = _getarg(request, b"total", 100, int)+ show = _getarg(request, b"show", 10, int)+ nlist = [random.randint(1, total) for _ in range(show)] # noqa: S311+ request.write(b"<html><head></head><body>")+ assert request.args is not None+ args = request.args.copy()+ for nl in nlist:+ args["n"] = nl+ argstr = urlencode(args, doseq=True)+ request.write(f"<a href='/follow?{argstr}'>follow {nl}</a><br>".encode())+ request.write(b"</body></html>")+ return b""+++def _getarg(+ request: Request, name: bytes, default: Any = None, type_: type = str+) -> Any:+ return type_(request.args[name][0]) if name in request.args else default+++# The bench command kills this process, so coverage data is never written for+# the lines below.+++def main() -> None: # pragma: no cover+ from twisted.internet import reactor++ root = Root() # type: ignore[no-untyped-call]+ httpPort = reactor.listenTCP(8998, Site(root))++ def _print_listening() -> None:+ httpHost = httpPort.getHost()+ print(f"Bench server at http://{httpHost.host}:{httpHost.port}")++ reactor.callWhenRunning(_print_listening)+ reactor.run()+++if __name__ == "__main__": # pragma: no cover+ main()diff --git a/scrapy/utils/_compression.py b/scrapy/utils/_compression.pyindex f3ab6cfe4..1966b4f1c 100644--- a/scrapy/utils/_compression.py+++ b/scrapy/utils/_compression.py@@ -1,6 +1,11 @@+from __future__ import annotations++import structimport sysimport zlib+from gzip import GzipFilefrom io import BytesIO+from typing import TYPE_CHECKINGtry:import brotli@@ -12,6 +17,9 @@ if sys.version_info >= (3, 14):else:from backports import zstd+if TYPE_CHECKING:+ from scrapy.http import Response+_CHUNK_SIZE = 65536 # 64 KiB@@ -34,6 +42,35 @@ def _check_max_size(decompressed_size: int, max_size: int) -> None:raise _DecompressionMaxSizeExceeded(decompressed_size, max_size)+def gunzip(data: bytes, *, max_size: int = 0) -> bytes:+ """Gunzip the given data and return as much data as possible.++ This is resilient to CRC checksum errors.+ """+ f = GzipFile(fileobj=BytesIO(data))+ output_stream = BytesIO()+ chunk = b"."+ decompressed_size = 0+ while chunk:+ try:+ chunk = f.read1(_CHUNK_SIZE)+ except (OSError, EOFError, struct.error):+ # complete only if there is some data, otherwise re-raise+ # see issue 87 about catching struct.error+ # some pages are quite small so output_stream is empty+ if output_stream.getbuffer().nbytes > 0:+ break+ raise+ decompressed_size += len(chunk)+ _check_max_size(decompressed_size, max_size)+ output_stream.write(chunk)+ return output_stream.getvalue()+++def gzip_magic_number(response: Response) -> bool:+ return response.body[:3] == b"\x1f\x8b\x08"++def _inflate(data: bytes, *, max_size: int = 0) -> bytes:decompressor = zlib.decompressobj()try:diff --git a/scrapy/utils/_shell.py b/scrapy/utils/_shell.pynew file mode 100644index 000000000..27730e1a3--- /dev/null+++ b/scrapy/utils/_shell.py@@ -0,0 +1,144 @@+from __future__ import annotations++import asyncio+import code+from collections.abc import Callable+from functools import partial, wraps+from typing import TYPE_CHECKING, Any, TypeAlias++if TYPE_CHECKING:+ from collections.abc import Iterable++EmbedFuncT: TypeAlias = Callable[..., None]+KnownShellsT: TypeAlias = dict[str, Callable[..., EmbedFuncT]]+++def _embed_ipython_shell(+ namespace: dict[str, Any] | None = None, banner: str = ""+) -> EmbedFuncT:+ """Start an IPython Shell"""+ from IPython.terminal.embed import InteractiveShellEmbed # noqa: T100,PLC0415+ from IPython.terminal.ipapp import load_default_config # noqa: PLC0415++ @wraps(_embed_ipython_shell)+ def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:+ config = load_default_config() # type: ignore[no-untyped-call]+ # Always use .instance() to ensure _instance propagation to all parents+ # this is needed for <TAB> completion works well for new imports+ # and clear the instance to always have the fresh env+ # on repeated breaks like with inspect_response()+ InteractiveShellEmbed.clear_instance()+ shell = InteractiveShellEmbed.instance(+ banner1=banner, user_ns=namespace, config=config+ )+ # If an asyncio event loop is already running in this thread, e.g. when+ # inspect_response() is called from a spider callback while using the+ # asyncio reactor, prompt_toolkit cannot run its own event loop here, so+ # ask it to run the prompt in a separate thread instead. pt_app is None+ # when IPython falls back to its simple prompt, which needs no event loop.+ # See https://github.com/scrapy/scrapy/issues/5447+ if (pt_app := getattr(shell, "pt_app", None)) is not None:+ try:+ asyncio.get_running_loop()+ except RuntimeError:+ pass+ else:+ pt_app.prompt = partial(pt_app.prompt, in_thread=True)+ shell()++ return wrapper+++def _embed_bpython_shell(+ namespace: dict[str, Any] | None = None, banner: str = ""+) -> EmbedFuncT:+ """Start a bpython shell"""+ import bpython # noqa: PLC0415++ @wraps(_embed_bpython_shell)+ def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:+ bpython.embed(locals_=namespace, banner=banner)++ return wrapper+++def _embed_ptpython_shell(+ namespace: dict[str, Any] | None = None, banner: str = ""+) -> EmbedFuncT:+ """Start a ptpython shell"""+ import ptpython.repl # noqa: PLC0415++ @wraps(_embed_ptpython_shell)+ def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:+ print(banner)+ ptpython.repl.embed(locals=namespace)++ return wrapper+++def _embed_standard_shell(+ namespace: dict[str, Any] | None = None, banner: str = ""+) -> EmbedFuncT:+ """Start a standard python shell"""+ try: # readline module is only available on unix systems+ import readline # noqa: PLC0415+ except ImportError:+ pass+ else:+ import rlcompleter # noqa: F401,PLC0415++ readline.parse_and_bind("tab:complete") # type: ignore[attr-defined,unused-ignore]++ @wraps(_embed_standard_shell)+ def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:+ code.interact(banner=banner, local=namespace)++ return wrapper+++DEFAULT_PYTHON_SHELLS: KnownShellsT = {+ "ptpython": _embed_ptpython_shell,+ "ipython": _embed_ipython_shell,+ "bpython": _embed_bpython_shell,+ "python": _embed_standard_shell,+}+++def get_shell_embed_func(+ shells: Iterable[str] | None = None, known_shells: KnownShellsT | None = None+) -> EmbedFuncT | None:+ """Return the first acceptable shell-embed function+ from a given list of shell names.+ """+ if shells is None: # list, preference order of shells+ shells = DEFAULT_PYTHON_SHELLS.keys()+ if known_shells is None: # available embeddable shells+ known_shells = DEFAULT_PYTHON_SHELLS.copy()+ for shell in shells:+ if shell in known_shells:+ try:+ # function test: run all setup code (imports),+ # but dont fall into the shell+ return known_shells[shell]()+ except ImportError:+ continue+ return None+++def start_python_console(+ namespace: dict[str, Any] | None = None,+ banner: str = "",+ shells: Iterable[str] | None = None,+) -> None:+ """Start Python console bound to the given namespace.+ Readline support and tab completion will be used on Unix, if available.+ """+ if namespace is None:+ namespace = {}++ try:+ shell = get_shell_embed_func(shells)+ if shell is not None:+ shell(namespace=namespace, banner=banner)+ except SystemExit: # raised when using exit() in python code.interact+ passdiff --git a/scrapy/utils/_ssl.py b/scrapy/utils/_ssl.pynew file mode 100644index 000000000..d15f80493--- /dev/null+++ b/scrapy/utils/_ssl.py@@ -0,0 +1,204 @@+from __future__ import annotations++import logging+import os+import ssl+import sys+from pathlib import Path+from typing import TYPE_CHECKING, TypedDict, TypeVar++from twisted.internet.ssl import CertificateOptions, TLSVersion++from scrapy.utils._deps_compat import TWISTED_TLS_LIMITS_OFFBY1++if TYPE_CHECKING:+ from collections.abc import Callable++ import OpenSSL.SSL++ from scrapy.settings import BaseSettings++logger = logging.getLogger(__name__)++_T = TypeVar("_T")+++# common+++def _get_tls_version_limit(+ settings: BaseSettings, setting_name: str, converter: Callable[[str], _T]+) -> _T | None:+ setting: str | None = settings[setting_name]+ if setting is None:+ return None+ try:+ return converter(setting)+ except Exception as ex:+ raise ValueError(f"Unknown {setting_name} value: {setting}") from ex+++def _get_tls_version_limits(+ settings: BaseSettings, converter: Callable[[str], _T]+) -> tuple[_T | None, _T | None]:+ return (+ _get_tls_version_limit(settings, "DOWNLOAD_TLS_MIN_VERSION", converter),+ _get_tls_version_limit(settings, "DOWNLOAD_TLS_MAX_VERSION", converter),+ )+++def _get_keylog_filename() -> str | None:+ """Return the path where TLS session keys should be logged, or ``None``."""+ if sys.flags.ignore_environment:+ return None+ filename = os.environ.get("SSLKEYLOGFILE")+ if not filename:+ return None+ try:+ with Path(filename).open("ab"):+ pass+ except OSError as ex:+ logger.warning(f"Cannot write TLS session keys to {filename}: {ex}")+ return None+ return filename+++# stdlib ssl module utils+++_STDLIB_VERSION_MAP: dict[str, ssl.TLSVersion] = {+ "TLSv1.0": ssl.TLSVersion.TLSv1,+ "TLSv1.1": ssl.TLSVersion.TLSv1_1,+ "TLSv1.2": ssl.TLSVersion.TLSv1_2,+ "TLSv1.3": ssl.TLSVersion.TLSv1_3,+}+++def _make_ssl_context(settings: BaseSettings) -> ssl.SSLContext:+ """Create an :class:`ssl.SSLContext` instance according to the settings.++ It's intended to be used in an HTTPS download handler.+ """++ tls_min_ver, tls_max_ver = _get_tls_version_limits(+ settings, _STDLIB_VERSION_MAP.__getitem__+ )+ ciphers_setting: str | None = settings["DOWNLOADER_CLIENT_TLS_CIPHERS"]+ verify_setting = settings.getbool("DOWNLOAD_VERIFY_CERTIFICATES")++ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)+ if verify_setting:+ ctx.check_hostname = True+ ctx.verify_mode = ssl.CERT_REQUIRED+ ctx.load_default_certs()+ else:+ ctx.check_hostname = False+ ctx.verify_mode = ssl.CERT_NONE+ if tls_min_ver is not None:+ ctx.minimum_version = tls_min_ver+ if tls_max_ver is not None:+ ctx.maximum_version = tls_max_ver+ if ciphers_setting:+ ctx.set_ciphers(ciphers_setting)+ if keylog_filename := _get_keylog_filename():+ ctx.keylog_filename = keylog_filename+ return ctx+++def _make_insecure_ssl_ctx() -> ssl.SSLContext:+ """Create an SSL context that doesn't verify certificates.++ Compared to :func:`~scrapy.utils._ssl._make_ssl_context` this is much more+ simple.+ """+ ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)+ ctx.check_hostname = False+ ctx.verify_mode = ssl.CERT_NONE+ if keylog_filename := _get_keylog_filename():+ ctx.keylog_filename = keylog_filename+ return ctx+++def _log_sslobj_debug_info(sslobj: ssl.SSLObject) -> None:+ cipher = sslobj.cipher()+ logger.debug(+ f"SSL connection to {sslobj.server_hostname}"+ f" using protocol {sslobj.version()},"+ f" cipher {cipher[0] if cipher else None}"+ )+ if cert := sslobj.getpeercert():+ # Not available without certificate verification+ logger.debug(+ f'SSL connection certificate: issuer "{cert["issuer"]}", subject "{cert["subject"]}"'+ )+++# pyOpenSSL utils+++def _set_keylog_callback(ctx: OpenSSL.SSL.Context) -> None:+ """Make *ctx* write TLS session keys to the key log file, if enabled."""+ keylog_filename = _get_keylog_filename()+ if not keylog_filename:+ return+ keylog_path = Path(keylog_filename)++ def write_keylog_line(connection: OpenSSL.SSL.Connection, line: bytes) -> None:+ with keylog_path.open("ab") as f:+ f.write(line + b"\n")++ ctx.set_keylog_callback(write_keylog_line)+++def _log_ssl_conn_debug_info(hostname: str, connection: OpenSSL.SSL.Connection) -> None:+ logger.debug(+ "SSL connection to %s using protocol %s, cipher %s",+ hostname,+ connection.get_protocol_version_name(),+ connection.get_cipher_name(),+ )+ if server_cert := connection.get_peer_certificate(as_cryptography=True):+ logger.debug(+ 'SSL connection certificate: issuer "%s", subject "%s"',+ server_cert.issuer.rfc4514_string(),+ server_cert.subject.rfc4514_string(),+ )+++# Twisted-specific+++class _CertificateOptionsVersionKwargs(TypedDict, total=False):+ lowerMaximumSecurityTo: TLSVersion+ insecurelyLowerMinimumTo: TLSVersion+ raiseMinimumTo: TLSVersion+++def _get_cert_options_version_kwargs(+ min_version: TLSVersion | None, max_version: TLSVersion | None+) -> _CertificateOptionsVersionKwargs:+ """Get TLS version kwargs for+ :class:`~twisted.internet.ssl.CertificateOptions` for the given limits."""+ result: _CertificateOptionsVersionKwargs = {}+ if max_version:+ if TWISTED_TLS_LIMITS_OFFBY1:+ # lowerMaximumSecurityTo is treated as 1 version lower than the passed one+ versions = list(TLSVersion.iterconstants())+ max_index = versions.index(max_version)+ if max_index + 1 >= len(versions):+ raise ValueError(+ f"Due to an error in Twisted < 26.4.0 cannot set the maximum TLS version to {max_version.name}"+ )+ max_version = versions[max_index + 1]+ result["lowerMaximumSecurityTo"] = max_version+ if min_version:+ # We cannot pass both insecurelyLowerMinimumTo and raiseMinimumTo,+ # so we need to know the direction.++ # 1.0 in Twisted 22.8.0 and older, 1.2 in Twisted 22.10.0 and newer+ default_min = CertificateOptions._defaultMinimumTLSVersion+ if min_version < default_min:+ result["insecurelyLowerMinimumTo"] = min_version+ elif min_version > default_min:+ result["raiseMinimumTo"] = min_version+ return resultdiff --git a/scrapy/utils/_versions.py b/scrapy/utils/_versions.pynew file mode 100644index 000000000..fc7c1d65e--- /dev/null+++ b/scrapy/utils/_versions.py@@ -0,0 +1,39 @@+from __future__ import annotations++import platform+import sys+from importlib.metadata import version++import lxml.etree+import OpenSSL.SSL+import OpenSSL.version++from scrapy.settings.default_settings import LOG_VERSIONS++_DEFAULT_SOFTWARE: list[str] = ["Scrapy", *LOG_VERSIONS]+++def _get_openssl_version() -> str:+ system_openssl_bytes = OpenSSL.SSL.SSLeay_version(OpenSSL.SSL.SSLEAY_VERSION)+ system_openssl = system_openssl_bytes.decode("ascii", errors="replace")+ return f"{OpenSSL.version.__version__} ({system_openssl})"+++def _version(item: str) -> str:+ lowercase_item = item.lower()+ if lowercase_item == "libxml2":+ return ".".join(map(str, lxml.etree.LIBXML_VERSION))+ if lowercase_item == "platform":+ return platform.platform()+ if lowercase_item == "pyopenssl":+ return _get_openssl_version()+ if lowercase_item == "python":+ return sys.version.replace("\n", "- ")+ return version(item)+++def get_versions(+ software: list[str] | None = None,+) -> list[tuple[str, str]]:+ software = software or _DEFAULT_SOFTWARE+ return [(item, _version(item)) for item in software]diff --git a/scrapy/utils/benchserver.py b/scrapy/utils/benchserver.pyindex 4055b6820..ec89efe10 100644--- a/scrapy/utils/benchserver.py+++ b/scrapy/utils/benchserver.py@@ -1,50 +1,20 @@-import random-from typing import Any-from urllib.parse import urlencode+# pragma: no file cover+import warnings-from twisted.web.resource import Resource-from twisted.web.server import Request, Site+from scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils._benchserver import Root, main+warnings.warn(+ "The scrapy.utils.benchserver module is deprecated.",+ ScrapyDeprecationWarning,+ stacklevel=2,+)-class Root(Resource):- isLeaf = True- def getChild(self, path: str, request: Request) -> Resource:- return self+__all__ = [+ "Root",+]- def render(self, request: Request) -> bytes:- total = _getarg(request, b"total", 100, int)- show = _getarg(request, b"show", 10, int)- nlist = [random.randint(1, total) for _ in range(show)] # noqa: S311- request.write(b"<html><head></head><body>")- assert request.args is not None- args = request.args.copy()- for nl in nlist:- args["n"] = nl- argstr = urlencode(args, doseq=True)- request.write(f"<a href='/follow?{argstr}'>follow {nl}</a><br>".encode())- request.write(b"</body></html>")- return b""--def _getarg(- request: Request, name: bytes, default: Any = None, type_: type = str-) -> Any:- return type_(request.args[name][0]) if name in request.args else default---# The bench command kills this process, so coverage data is never written for-# the lines below.-if __name__ == "__main__": # pragma: no cover- from twisted.internet import reactor-- root = Root() # type: ignore[no-untyped-call]- factory = Site(root)- httpPort = reactor.listenTCP(8998, Site(root))-- def _print_listening() -> None:- httpHost = httpPort.getHost()- print(f"Bench server at http://{httpHost.host}:{httpHost.port}")-- reactor.callWhenRunning(_print_listening)- reactor.run()+if __name__ == "__main__":+ main()diff --git a/scrapy/utils/conf.py b/scrapy/utils/conf.pyindex 2b407c8a7..ecfdd0394 100644--- a/scrapy/utils/conf.py+++ b/scrapy/utils/conf.py@@ -198,3 +198,12 @@ def feed_process_params_from_cli(result.update(settings.getdict("FEEDS"))return result+++def _job_dir(settings: BaseSettings) -> str | None:+ path: str | None = settings["JOBDIR"]+ if not path:+ return None+ if not Path(path).exists():+ Path(path).mkdir(parents=True)+ return pathdiff --git a/scrapy/utils/console.py b/scrapy/utils/console.pyindex 27730e1a3..49159b522 100644--- a/scrapy/utils/console.py+++ b/scrapy/utils/console.py@@ -1,144 +1,25 @@-from __future__ import annotations--import asyncio-import code-from collections.abc import Callable-from functools import partial, wraps-from typing import TYPE_CHECKING, Any, TypeAlias--if TYPE_CHECKING:- from collections.abc import Iterable--EmbedFuncT: TypeAlias = Callable[..., None]-KnownShellsT: TypeAlias = dict[str, Callable[..., EmbedFuncT]]---def _embed_ipython_shell(- namespace: dict[str, Any] | None = None, banner: str = ""-) -> EmbedFuncT:- """Start an IPython Shell"""- from IPython.terminal.embed import InteractiveShellEmbed # noqa: T100,PLC0415- from IPython.terminal.ipapp import load_default_config # noqa: PLC0415-- @wraps(_embed_ipython_shell)- def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:- config = load_default_config() # type: ignore[no-untyped-call]- # Always use .instance() to ensure _instance propagation to all parents- # this is needed for <TAB> completion works well for new imports- # and clear the instance to always have the fresh env- # on repeated breaks like with inspect_response()- InteractiveShellEmbed.clear_instance()- shell = InteractiveShellEmbed.instance(- banner1=banner, user_ns=namespace, config=config- )- # If an asyncio event loop is already running in this thread, e.g. when- # inspect_response() is called from a spider callback while using the- # asyncio reactor, prompt_toolkit cannot run its own event loop here, so- # ask it to run the prompt in a separate thread instead. pt_app is None- # when IPython falls back to its simple prompt, which needs no event loop.- # See https://github.com/scrapy/scrapy/issues/5447- if (pt_app := getattr(shell, "pt_app", None)) is not None:- try:- asyncio.get_running_loop()- except RuntimeError:- pass- else:- pt_app.prompt = partial(pt_app.prompt, in_thread=True)- shell()-- return wrapper---def _embed_bpython_shell(- namespace: dict[str, Any] | None = None, banner: str = ""-) -> EmbedFuncT:- """Start a bpython shell"""- import bpython # noqa: PLC0415-- @wraps(_embed_bpython_shell)- def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:- bpython.embed(locals_=namespace, banner=banner)-- return wrapper---def _embed_ptpython_shell(- namespace: dict[str, Any] | None = None, banner: str = ""-) -> EmbedFuncT:- """Start a ptpython shell"""- import ptpython.repl # noqa: PLC0415-- @wraps(_embed_ptpython_shell)- def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:- print(banner)- ptpython.repl.embed(locals=namespace)-- return wrapper---def _embed_standard_shell(- namespace: dict[str, Any] | None = None, banner: str = ""-) -> EmbedFuncT:- """Start a standard python shell"""- try: # readline module is only available on unix systems- import readline # noqa: PLC0415- except ImportError:- pass- else:- import rlcompleter # noqa: F401,PLC0415-- readline.parse_and_bind("tab:complete") # type: ignore[attr-defined,unused-ignore]-- @wraps(_embed_standard_shell)- def wrapper(namespace: dict[str, Any] = namespace or {}, banner: str = "") -> None:- code.interact(banner=banner, local=namespace)-- return wrapper---DEFAULT_PYTHON_SHELLS: KnownShellsT = {- "ptpython": _embed_ptpython_shell,- "ipython": _embed_ipython_shell,- "bpython": _embed_bpython_shell,- "python": _embed_standard_shell,-}---def get_shell_embed_func(- shells: Iterable[str] | None = None, known_shells: KnownShellsT | None = None-) -> EmbedFuncT | None:- """Return the first acceptable shell-embed function- from a given list of shell names.- """- if shells is None: # list, preference order of shells- shells = DEFAULT_PYTHON_SHELLS.keys()- if known_shells is None: # available embeddable shells- known_shells = DEFAULT_PYTHON_SHELLS.copy()- for shell in shells:- if shell in known_shells:- try:- # function test: run all setup code (imports),- # but dont fall into the shell- return known_shells[shell]()- except ImportError:- continue- return None---def start_python_console(- namespace: dict[str, Any] | None = None,- banner: str = "",- shells: Iterable[str] | None = None,-) -> None:- """Start Python console bound to the given namespace.- Readline support and tab completion will be used on Unix, if available.- """- if namespace is None:- namespace = {}-- try:- shell = get_shell_embed_func(shells)- if shell is not None:- shell(namespace=namespace, banner=banner)- except SystemExit: # raised when using exit() in python code.interact- pass+# pragma: no file cover+import warnings++from scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils._shell import (+ DEFAULT_PYTHON_SHELLS,+ EmbedFuncT,+ KnownShellsT,+ get_shell_embed_func,+ start_python_console,+)++warnings.warn(+ "The scrapy.utils.console module is deprecated.",+ ScrapyDeprecationWarning,+ stacklevel=2,+)++__all__ = [+ "DEFAULT_PYTHON_SHELLS",+ "EmbedFuncT",+ "KnownShellsT",+ "get_shell_embed_func",+ "start_python_console",+]diff --git a/scrapy/utils/gz.py b/scrapy/utils/gz.pyindex 5f95bccbd..db9df60c4 100644--- a/scrapy/utils/gz.py+++ b/scrapy/utils/gz.py@@ -1,40 +1,16 @@-from __future__ import annotations--import struct-from gzip import GzipFile-from io import BytesIO-from typing import TYPE_CHECKING--from ._compression import _CHUNK_SIZE, _check_max_size--if TYPE_CHECKING:- from scrapy.http import Response---def gunzip(data: bytes, *, max_size: int = 0) -> bytes:- """Gunzip the given data and return as much data as possible.-- This is resilient to CRC checksum errors.- """- f = GzipFile(fileobj=BytesIO(data))- output_stream = BytesIO()- chunk = b"."- decompressed_size = 0- while chunk:- try:- chunk = f.read1(_CHUNK_SIZE)- except (OSError, EOFError, struct.error):- # complete only if there is some data, otherwise re-raise- # see issue 87 about catching struct.error- # some pages are quite small so output_stream is empty- if output_stream.getbuffer().nbytes > 0:- break- raise- decompressed_size += len(chunk)- _check_max_size(decompressed_size, max_size)- output_stream.write(chunk)- return output_stream.getvalue()---def gzip_magic_number(response: Response) -> bool:- return response.body[:3] == b"\x1f\x8b\x08"+# pragma: no file cover+import warnings++from scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils._compression import gunzip, gzip_magic_number++warnings.warn(+ "The scrapy.utils.gz module is deprecated.",+ ScrapyDeprecationWarning,+ stacklevel=2,+)++__all__ = [+ "gunzip",+ "gzip_magic_number",+]diff --git a/scrapy/utils/job.py b/scrapy/utils/job.pyindex 37e6aeb51..c15f4142a 100644--- a/scrapy/utils/job.py+++ b/scrapy/utils/job.py@@ -1,16 +1,15 @@-from __future__ import annotations+# pragma: no file cover+import warnings-from pathlib import Path-from typing import TYPE_CHECKING+from scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils.conf import _job_dir as job_dir-if TYPE_CHECKING:- from scrapy.settings import BaseSettings+warnings.warn(+ "The scrapy.utils.job module is deprecated.",+ ScrapyDeprecationWarning,+ stacklevel=2,+)--def job_dir(settings: BaseSettings) -> str | None:- path: str | None = settings["JOBDIR"]- if not path:- return None- if not Path(path).exists():- Path(path).mkdir(parents=True)- return path+__all__ = [+ "job_dir",+]diff --git a/scrapy/utils/log.py b/scrapy/utils/log.pyindex 9d0e95da3..bb4254f0c 100644--- a/scrapy/utils/log.py+++ b/scrapy/utils/log.py@@ -16,8 +16,8 @@ from twisted.python.failure import Failureimport scrapyfrom scrapy.exceptions import ScrapyDeprecationWarningfrom scrapy.settings import Settings+from scrapy.utils._versions import get_versionsfrom scrapy.utils.display import _tty_supports_color-from scrapy.utils.versions import get_versionsif TYPE_CHECKING:from types import TracebackTypediff --git a/scrapy/utils/misc.py b/scrapy/utils/misc.pyindex 7956a99df..338649b65 100644--- a/scrapy/utils/misc.py+++ b/scrapy/utils/misc.py@@ -100,13 +100,13 @@ def walk_modules_iter(path: str) -> Iterable[ModuleType]:exception is thrown back.For example:- >>> list(walk_modules_iter('scrapy.utils'))- [<module 'scrapy.utils' from '...'>, ...]- >>> gen = walk_modules_iter('scrapy.utils.nonexistent') # error not raised until the generator is consumed+ >>> list(walk_modules_iter('scrapy.commands'))+ [<module 'scrapy.commands' from '...'>, ...]+ >>> gen = walk_modules_iter('scrapy.commands.nonexistent') # error not raised until the generator is consumed>>> list(gen)Traceback (most recent call last):...- ModuleNotFoundError: No module named 'scrapy.utils.nonexistent'...+ ModuleNotFoundError: No module named 'scrapy.commands.nonexistent'..."""mod = import_module(path)diff --git a/scrapy/utils/ssl.py b/scrapy/utils/ssl.pyindex 63f3207a7..fca4f75fa 100644--- a/scrapy/utils/ssl.py+++ b/scrapy/utils/ssl.py@@ -1,257 +1,47 @@+# pragma: no file coverfrom __future__ import annotations-import logging-import os-import ssl-import sysimport warnings-from pathlib import Path-from typing import TYPE_CHECKING, Any, TypedDict, TypeVar+from typing import TYPE_CHECKING, Anyimport OpenSSL._util as pyOpenSSLutil-import OpenSSL.SSL-import OpenSSL.version-from twisted.internet.ssl import CertificateOptions, TLSVersionfrom scrapy.exceptions import ScrapyDeprecationWarning-from scrapy.utils._deps_compat import TWISTED_TLS_LIMITS_OFFBY1+from scrapy.utils._versions import _get_openssl_version as get_openssl_versionfrom scrapy.utils.python import to_unicodeif TYPE_CHECKING:- from collections.abc import Callable-from OpenSSL.crypto import X509Name- from scrapy.settings import BaseSettings--logger = logging.getLogger(__name__)--_T = TypeVar("_T")---# common---def _get_tls_version_limit(- settings: BaseSettings, setting_name: str, converter: Callable[[str], _T]-) -> _T | None:- setting: str | None = settings[setting_name]- if setting is None:- return None- try:- return converter(setting)- except Exception as ex:- raise ValueError(f"Unknown {setting_name} value: {setting}") from ex---def _get_tls_version_limits(- settings: BaseSettings, converter: Callable[[str], _T]-) -> tuple[_T | None, _T | None]:- return (- _get_tls_version_limit(settings, "DOWNLOAD_TLS_MIN_VERSION", converter),- _get_tls_version_limit(settings, "DOWNLOAD_TLS_MAX_VERSION", converter),- )---def _get_keylog_filename() -> str | None:- """Return the path where TLS session keys should be logged, or ``None``."""- if sys.flags.ignore_environment:- return None- filename = os.environ.get("SSLKEYLOGFILE")- if not filename:- return None- try:- with Path(filename).open("ab"):- pass- except OSError as ex:- logger.warning(f"Cannot write TLS session keys to {filename}: {ex}")- return None- return filename---# stdlib ssl module utils--_STDLIB_VERSION_MAP: dict[str, ssl.TLSVersion] = {- "TLSv1.0": ssl.TLSVersion.TLSv1,- "TLSv1.1": ssl.TLSVersion.TLSv1_1,- "TLSv1.2": ssl.TLSVersion.TLSv1_2,- "TLSv1.3": ssl.TLSVersion.TLSv1_3,-}---def _make_ssl_context(settings: BaseSettings) -> ssl.SSLContext:- """Create an :class:`ssl.SSLContext` instance according to the settings.-- It's intended to be used in an HTTPS download handler.- """-- tls_min_ver, tls_max_ver = _get_tls_version_limits(- settings, _STDLIB_VERSION_MAP.__getitem__- )- ciphers_setting: str | None = settings["DOWNLOADER_CLIENT_TLS_CIPHERS"]- verify_setting = settings.getbool("DOWNLOAD_VERIFY_CERTIFICATES")-- ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)- if verify_setting:- ctx.check_hostname = True- ctx.verify_mode = ssl.CERT_REQUIRED- ctx.load_default_certs()- else:- ctx.check_hostname = False- ctx.verify_mode = ssl.CERT_NONE- if tls_min_ver is not None:- ctx.minimum_version = tls_min_ver- if tls_max_ver is not None:- ctx.maximum_version = tls_max_ver- if ciphers_setting:- ctx.set_ciphers(ciphers_setting)- if keylog_filename := _get_keylog_filename():- ctx.keylog_filename = keylog_filename- return ctx---def _make_insecure_ssl_ctx() -> ssl.SSLContext:- """Create an SSL context that doesn't verify certificates.-- Compared to :func:`~scrapy.utils.ssl._make_ssl_context` this is much more- simple.- """- ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)- ctx.check_hostname = False- ctx.verify_mode = ssl.CERT_NONE- if keylog_filename := _get_keylog_filename():- ctx.keylog_filename = keylog_filename- return ctx---def _log_sslobj_debug_info(sslobj: ssl.SSLObject) -> None:- cipher = sslobj.cipher()- logger.debug(- f"SSL connection to {sslobj.server_hostname}"- f" using protocol {sslobj.version()},"- f" cipher {cipher[0] if cipher else None}"- )- if cert := sslobj.getpeercert():- # Not available without certificate verification- logger.debug(- f'SSL connection certificate: issuer "{cert["issuer"]}", subject "{cert["subject"]}"'- )---# pyOpenSSL utils---def _set_keylog_callback(ctx: OpenSSL.SSL.Context) -> None:- """Make *ctx* write TLS session keys to the key log file, if enabled."""- keylog_filename = _get_keylog_filename()- if not keylog_filename:- return- keylog_path = Path(keylog_filename)- def write_keylog_line(connection: OpenSSL.SSL.Connection, line: bytes) -> None:- with keylog_path.open("ab") as f:- f.write(line + b"\n")-- ctx.set_keylog_callback(write_keylog_line)---def _ffi_buf_to_string(buf: Any) -> str:- return to_unicode(pyOpenSSLutil.ffi.string(buf))+def get_temp_key_info(ssl_object: Any) -> str | None:+ # A no-op: it read the negotiated ephemeral key through a binding that+ # cryptography 40.0.0 removed.+ return Nonedef ffi_buf_to_string(buf: Any) -> str:- warnings.warn(- "ffi_buf_to_string() is deprecated.",- ScrapyDeprecationWarning,- stacklevel=2,- )- return _ffi_buf_to_string(buf)+ return to_unicode(pyOpenSSLutil.ffi.string(buf))-def _x509name_to_string(x509name: X509Name) -> str:+def x509name_to_string(x509name: X509Name) -> str:# from OpenSSL.crypto.X509Name.__repr__result_buffer: Any = pyOpenSSLutil.ffi.new("char[]", 512)pyOpenSSLutil.lib.X509_NAME_oneline(x509name._name, result_buffer, len(result_buffer))- return _ffi_buf_to_string(result_buffer)---def x509name_to_string(x509name: X509Name) -> str:- warnings.warn(- "x509name_to_string() is deprecated.",- ScrapyDeprecationWarning,- stacklevel=2,- )- return _x509name_to_string(x509name)---def get_temp_key_info(ssl_object: Any) -> str | None:- # A no-op: it read the negotiated ephemeral key through a binding that- # cryptography 40.0.0 removed.- warnings.warn(- "get_temp_key_info() is deprecated. It's also a no-op with cryptography 40.0.0+.",- ScrapyDeprecationWarning,- stacklevel=2,- )- return None---def get_openssl_version() -> str:- system_openssl_bytes = OpenSSL.SSL.SSLeay_version(OpenSSL.SSL.SSLEAY_VERSION)- system_openssl = system_openssl_bytes.decode("ascii", errors="replace")- return f"{OpenSSL.version.__version__} ({system_openssl})"---def _log_ssl_conn_debug_info(hostname: str, connection: OpenSSL.SSL.Connection) -> None:- logger.debug(- "SSL connection to %s using protocol %s, cipher %s",- hostname,- connection.get_protocol_version_name(),- connection.get_cipher_name(),- )- if server_cert := connection.get_peer_certificate(as_cryptography=True):- logger.debug(- 'SSL connection certificate: issuer "%s", subject "%s"',- server_cert.issuer.rfc4514_string(),- server_cert.subject.rfc4514_string(),- )---# Twisted-specific---class _CertificateOptionsVersionKwargs(TypedDict, total=False):- lowerMaximumSecurityTo: TLSVersion- insecurelyLowerMinimumTo: TLSVersion- raiseMinimumTo: TLSVersion+ return ffi_buf_to_string(result_buffer)-def _get_cert_options_version_kwargs(- min_version: TLSVersion | None, max_version: TLSVersion | None-) -> _CertificateOptionsVersionKwargs:- """Get TLS version kwargs for- :class:`~twisted.internet.ssl.CertificateOptions` for the given limits."""- result: _CertificateOptionsVersionKwargs = {}- if max_version:- if TWISTED_TLS_LIMITS_OFFBY1:- # lowerMaximumSecurityTo is treated as 1 version lower than the passed one- versions = list(TLSVersion.iterconstants())- max_index = versions.index(max_version)- if max_index + 1 >= len(versions):- raise ValueError(- f"Due to an error in Twisted < 26.4.0 cannot set the maximum TLS version to {max_version.name}"- )- max_version = versions[max_index + 1]- result["lowerMaximumSecurityTo"] = max_version- if min_version:- # We cannot pass both insecurelyLowerMinimumTo and raiseMinimumTo,- # so we need to know the direction.+warnings.warn(+ "The scrapy.utils.ssl module is deprecated.",+ ScrapyDeprecationWarning,+ stacklevel=2,+)- # 1.0 in Twisted 22.8.0 and older, 1.2 in Twisted 22.10.0 and newer- default_min = CertificateOptions._defaultMinimumTLSVersion- if min_version < default_min:- result["insecurelyLowerMinimumTo"] = min_version- elif min_version > default_min:- result["raiseMinimumTo"] = min_version- return result+__all__ = [+ "ffi_buf_to_string",+ "get_openssl_version",+ "get_temp_key_info",+ "x509name_to_string",+]diff --git a/scrapy/utils/versions.py b/scrapy/utils/versions.pyindex 6bd96a215..d3a23cb03 100644--- a/scrapy/utils/versions.py+++ b/scrapy/utils/versions.py@@ -1,32 +1,15 @@-from __future__ import annotations+# pragma: no file cover+import warnings-import platform-import sys-from importlib.metadata import version+from scrapy.exceptions import ScrapyDeprecationWarning+from scrapy.utils._versions import get_versions-import lxml.etree+warnings.warn(+ "The scrapy.utils.versions module is deprecated.",+ ScrapyDeprecationWarning,+ stacklevel=2,+)-from scrapy.settings.default_settings import LOG_VERSIONS-from scrapy.utils.ssl import get_openssl_version--_DEFAULT_SOFTWARE: list[str] = ["Scrapy", *LOG_VERSIONS]---def _version(item: str) -> str:- lowercase_item = item.lower()- if lowercase_item == "libxml2":- return ".".join(map(str, lxml.etree.LIBXML_VERSION))- if lowercase_item == "platform":- return platform.platform()- if lowercase_item == "pyopenssl":- return get_openssl_version()- if lowercase_item == "python":- return sys.version.replace("\n", "- ")- return version(item)---def get_versions(- software: list[str] | None = None,-) -> list[tuple[str, str]]:- software = software or _DEFAULT_SOFTWARE- return [(item, _version(item)) for item in software]+__all__ = [+ "get_versions",+]diff --git a/tests/benchmarks/test_httpcompression.py b/tests/benchmarks/test_httpcompression.pyindex f37cc341a..dfbdddb69 100644--- a/tests/benchmarks/test_httpcompression.py+++ b/tests/benchmarks/test_httpcompression.py@@ -9,7 +9,7 @@ import pytestfrom scrapy import Request, Spiderfrom scrapy.http import Response-from scrapy.utils.gz import gunzip+from scrapy.utils._compression import gunzipfrom tests import get_testdatafrom tests.benchmarks import crawldiff --git a/tests/ignores.txt b/tests/ignores.txtindex 5be8576f3..75ae2d141 100644--- a/tests/ignores.txt+++ b/tests/ignores.txt@@ -2,3 +2,9 @@ scrapy/core/downloader/handlers/http.pyscrapy/extensions/statsmailer.pyscrapy/interfaces.pyscrapy/mail.py+scrapy/utils/benchserver.py+scrapy/utils/console.py+scrapy/utils/gz.py+scrapy/utils/job.py+scrapy/utils/ssl.py+scrapy/utils/versions.pydiff --git a/tests/mockserver/utils.py b/tests/mockserver/utils.pyindex e993bedb2..a04ce8c28 100644--- a/tests/mockserver/utils.py+++ b/tests/mockserver/utils.py@@ -10,8 +10,8 @@ from OpenSSL import SSLfrom twisted.internet.ssl import CertificateOptions, ContextFactoryfrom scrapy.core.downloader.tls import _TWISTED_VERSION_MAP+from scrapy.utils._ssl import _get_cert_options_version_kwargsfrom scrapy.utils.python import to_bytes-from scrapy.utils.ssl import _get_cert_options_version_kwargsif TYPE_CHECKING:from twisted.internet.interfaces import IOpenSSLContextFactorydiff --git a/tests/test_downloadermiddleware_httpcompression.py b/tests/test_downloadermiddleware_httpcompression.pyindex f80a1224f..285982c46 100644--- a/tests/test_downloadermiddleware_httpcompression.py+++ b/tests/test_downloadermiddleware_httpcompression.py@@ -17,8 +17,7 @@ from scrapy.exceptions import IgnoreRequest, NotConfigured, ScrapyDeprecationWarfrom scrapy.http import HtmlResponse, Request, Responsefrom scrapy.responsetypes import responsetypesfrom scrapy.spiders import Spider-from scrapy.utils._compression import _CHUNK_SIZE, _DecompressionMaxSizeExceeded-from scrapy.utils.gz import gunzip+from scrapy.utils._compression import _CHUNK_SIZE, _DecompressionMaxSizeExceeded, gunzipfrom scrapy.utils.misc import build_from_crawlerfrom scrapy.utils.test import get_crawlerfrom tests import tests_datadirdiff --git a/tests/test_utils_benchserver.py b/tests/test_utils_benchserver.pyindex 68065a9dc..c88d6194c 100644--- a/tests/test_utils_benchserver.py+++ b/tests/test_utils_benchserver.py@@ -3,7 +3,7 @@ from __future__ import annotationsimport refrom typing import TYPE_CHECKING, cast-from scrapy.utils.benchserver import Root, _getarg+from scrapy.utils._benchserver import Root, _getargif TYPE_CHECKING:from twisted.web.server import Requestdiff --git a/tests/test_utils_gz.py b/tests/test_utils_compression.pysimilarity index 96%rename from tests/test_utils_gz.pyrename to tests/test_utils_compression.pyindex 75f8be6f6..bde16ec3c 100644--- a/tests/test_utils_gz.py+++ b/tests/test_utils_compression.py@@ -7,7 +7,7 @@ import pytestfrom w3lib.encoding import html_to_unicodefrom scrapy.http import Response-from scrapy.utils.gz import gunzip, gzip_magic_number+from scrapy.utils._compression import gunzip, gzip_magic_numberfrom tests import tests_datadirSAMPLEDIR = Path(tests_datadir, "compressed")diff --git a/tests/test_utils_conf.py b/tests/test_utils_conf.pyindex 6c2cda95b..01e76a25b 100644--- a/tests/test_utils_conf.py+++ b/tests/test_utils_conf.py@@ -1,12 +1,13 @@from __future__ import annotations-from typing import Any+from typing import TYPE_CHECKING, Anyimport pytestfrom scrapy.exceptions import UsageErrorfrom scrapy.settings import BaseSettings, Settingsfrom scrapy.utils.conf import (+ _job_dir,arglist_to_dict,build_component_list,closest_scrapy_cfg,@@ -15,6 +16,9 @@ from scrapy.utils.conf import (get_sources,)+if TYPE_CHECKING:+ from pathlib import Path+class TestBuildComponentList:def test_build_dict(self):@@ -197,3 +201,18 @@ class TestFeedExportConfig:feed, Settings(), "stdout:")assert new_feed["format"] == ""+++def test_no_jobdir() -> None:+ assert _job_dir(Settings()) is None+ assert _job_dir(Settings({"JOBDIR": ""})) is None+++def test_existing_jobdir(tmp_path: Path) -> None:+ assert _job_dir(Settings({"JOBDIR": str(tmp_path)})) == str(tmp_path)+++def test_missing_jobdir(tmp_path: Path) -> None:+ jobdir = tmp_path / "missing" / "jobdir"+ assert _job_dir(Settings({"JOBDIR": str(jobdir)})) == str(jobdir)+ assert jobdir.is_dir()diff --git a/tests/test_utils_job.py b/tests/test_utils_job.pydeleted file mode 100644index 31adc1514..000000000--- a/tests/test_utils_job.py+++ /dev/null@@ -1,24 +0,0 @@-from __future__ import annotations--from typing import TYPE_CHECKING--from scrapy.settings import Settings-from scrapy.utils.job import job_dir--if TYPE_CHECKING:- from pathlib import Path---def test_no_jobdir() -> None:- assert job_dir(Settings()) is None- assert job_dir(Settings({"JOBDIR": ""})) is None---def test_existing_jobdir(tmp_path: Path) -> None:- assert job_dir(Settings({"JOBDIR": str(tmp_path)})) == str(tmp_path)---def test_missing_jobdir(tmp_path: Path) -> None:- jobdir = tmp_path / "missing" / "jobdir"- assert job_dir(Settings({"JOBDIR": str(jobdir)})) == str(jobdir)- assert jobdir.is_dir()diff --git a/tests/test_utils_console.py b/tests/test_utils_shell.pysimilarity index 96%rename from tests/test_utils_console.pyrename to tests/test_utils_shell.pyindex 5ff1b0173..bb28e8b44 100644--- a/tests/test_utils_console.py+++ b/tests/test_utils_shell.py@@ -10,7 +10,7 @@ from typing import TYPE_CHECKINGimport pytestfrom pexpect import EOF-from scrapy.utils.console import get_shell_embed_func, start_python_console+from scrapy.utils._shell import get_shell_embed_func, start_python_consolefrom scrapy.utils.test import get_testenvif TYPE_CHECKING:@@ -198,13 +198,11 @@ def test_start_python_console_exit(monkeypatch: pytest.MonkeyPatch) -> None:raise SystemExitmonkeypatch.setattr(- "scrapy.utils.console.get_shell_embed_func", lambda shells: embed+ "scrapy.utils._shell.get_shell_embed_func", lambda shells: embed)start_python_console()def test_start_python_console_no_shell(monkeypatch: pytest.MonkeyPatch) -> None:- monkeypatch.setattr(- "scrapy.utils.console.get_shell_embed_func", lambda shells: None- )+ monkeypatch.setattr("scrapy.utils._shell.get_shell_embed_func", lambda shells: None)start_python_console()diff --git a/tests/test_utils_ssl.py b/tests/test_utils_ssl.pyindex 8e90f7b3e..d9a19010b 100644--- a/tests/test_utils_ssl.py+++ b/tests/test_utils_ssl.py@@ -1,57 +1,14 @@from __future__ import annotationsimport logging-import warnings-from typing import cast+from typing import TYPE_CHECKING, castfrom unittest import mock-import OpenSSL._util as pyOpenSSLutil-import OpenSSL.SSL-import pytest-from OpenSSL import crypto+from scrapy.utils._ssl import _log_ssl_conn_debug_info-from scrapy.exceptions import ScrapyDeprecationWarning-from scrapy.utils.ssl import (- _log_ssl_conn_debug_info,- ffi_buf_to_string,- get_openssl_version,- get_temp_key_info,- x509name_to_string,-)---def test_ffi_buf_to_string() -> None:- buf = pyOpenSSLutil.ffi.new("char[]", b"some text")- with pytest.warns(- ScrapyDeprecationWarning, match=r"ffi_buf_to_string\(\) is deprecated"- ):- assert ffi_buf_to_string(buf) == "some text"---def test_x509name_to_string() -> None:- with warnings.catch_warnings():- # X509 itself is deprecated in pyOpenSSL, but it is the only way to build- # the X509Name that the deprecated function under test takes.- warnings.simplefilter("ignore", DeprecationWarning)- subject = crypto.X509().get_subject()- subject.C = "IE"- subject.O = "Scrapy"- subject.CN = "localhost"- with pytest.warns(- ScrapyDeprecationWarning, match=r"x509name_to_string\(\) is deprecated"- ):- assert x509name_to_string(subject) == "/C=IE/O=Scrapy/CN=localhost"---def test_get_temp_key_info() -> None:- with pytest.warns(- ScrapyDeprecationWarning, match=r"get_temp_key_info\(\) is deprecated"- ):- assert get_temp_key_info(object()) is None---def test_get_openssl_version() -> None:- assert "OpenSSL" in get_openssl_version()+if TYPE_CHECKING:+ import OpenSSL.SSL+ import pytestdef test_log_ssl_conn_debug_info_no_certificate(@@ -61,7 +18,7 @@ def test_log_ssl_conn_debug_info_no_certificate(connection.get_protocol_version_name.return_value = "TLSv1.3"connection.get_cipher_name.return_value = "TLS_AES_256_GCM_SHA384"connection.get_peer_certificate.return_value = None- with caplog.at_level(logging.DEBUG, logger="scrapy.utils.ssl"):+ with caplog.at_level(logging.DEBUG, logger="scrapy.utils._ssl"):_log_ssl_conn_debug_info("example.com", cast("OpenSSL.SSL.Connection", connection))diff --git a/tests/test_utils_versions.py b/tests/test_utils_versions.pynew file mode 100644index 000000000..da9a47c58--- /dev/null+++ b/tests/test_utils_versions.py@@ -0,0 +1,5 @@+from scrapy.utils._versions import _get_openssl_version+++def test_get_openssl_version() -> None:+ assert "OpenSSL" in _get_openssl_version()