Scrapy, a fast high-level web crawling & scraping framework for Python.
Implement some idioms from newer Python versions. (#8123)
Andrey Rakhmatullin20dcf8287682
diff --git a/scrapy/__init__.py b/scrapy/__init__.pyindex c5b6483e3..d8d40a8f2 100644--- a/scrapy/__init__.py+++ b/scrapy/__init__.py@@ -2,9 +2,9 @@Scrapy - a web crawling and web scraping framework written for Python"""-import pkgutilimport sysimport warnings+from importlib.resources import files# Declare top-level shortcutsfrom scrapy.http import FormRequest, Request@@ -25,7 +25,7 @@ __all__ = [# Scrapy and Twisted versions-__version__ = (pkgutil.get_data(__package__, "VERSION") or b"").decode("ascii").strip()+__version__ = files("scrapy").joinpath("VERSION").read_text(encoding="ascii").strip()version_info = tuple(int(v) if v.isdigit() else v for v in __version__.split("."))@@ -33,6 +33,6 @@ version_info = tuple(int(v) if v.isdigit() else v for v in __version__.split("."warnings.filterwarnings("ignore", category=DeprecationWarning, module="twisted")-del pkgutil+del filesdel sysdel warningsdiff --git a/scrapy/commands/__init__.py b/scrapy/commands/__init__.pyindex e8e446ba4..08213b574 100644--- a/scrapy/commands/__init__.py+++ b/scrapy/commands/__init__.py@@ -276,13 +276,15 @@ class ScrapyHelpFormatter(argparse.HelpFormatter):Underline and title case command line help message headers."""if part_strings and part_strings[0].startswith("usage: "):- part_strings[0] = "Usage\n=====\n " + part_strings[0][len("usage: ") :]+ part_strings[0] = "Usage\n=====\n " + part_strings[0].removeprefix(+ "usage: "+ )headings = [i for i in range(len(part_strings)) if part_strings[i].endswith(":\n")]for index in reversed(headings):char = "-" if "Global Options" in part_strings[index] else "="- part_strings[index] = part_strings[index][:-2].title()+ part_strings[index] = part_strings[index].removesuffix(":\n").title()underline = "".join(["\n", (char * len(part_strings[index])), "\n"])part_strings.insert(index + 1, underline)return part_stringsdiff --git a/scrapy/core/_http2/agent.py b/scrapy/core/_http2/agent.pyindex 0c769a865..e02d783b2 100644--- a/scrapy/core/_http2/agent.py+++ b/scrapy/core/_http2/agent.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom collections import deque-from typing import TYPE_CHECKING+from typing import TYPE_CHECKING, TypeAliasfrom twisted.internet import deferfrom twisted.internet.defer import Deferred@@ -21,7 +21,7 @@ if TYPE_CHECKING:from scrapy.spiders import Spider-ConnectionKeyT = tuple[bytes, bytes, int, tuple[str, int] | None]+ConnectionKey: TypeAlias = tuple[bytes, bytes, int, tuple[str, int] | None]class H2ConnectionPool:@@ -30,11 +30,11 @@ class H2ConnectionPool:# Store a dictionary which is used to get the respective# H2ClientProtocolInstance using the key as Tuple(scheme, hostname, port)- self._connections: dict[ConnectionKeyT, H2ClientProtocol] = {}+ self._connections: dict[ConnectionKey, H2ClientProtocol] = {}# Save all requests that arrive before the connection is establishedself._pending_requests: dict[- ConnectionKeyT, deque[Deferred[H2ClientProtocol]]+ ConnectionKey, deque[Deferred[H2ClientProtocol]]] = {}self._tls_verbose_logging: bool = crawler.settings.getbool(@@ -42,7 +42,7 @@ class H2ConnectionPool:)def get_connection(- self, key: ConnectionKeyT, uri: URI, endpoint: HostnameEndpoint+ self, key: ConnectionKey, uri: URI, endpoint: HostnameEndpoint) -> Deferred[H2ClientProtocol]:if key in self._pending_requests:# Received a request while connecting to remote@@ -62,7 +62,7 @@ class H2ConnectionPool:return self._new_connection(key, uri, endpoint)def _new_connection(- self, key: ConnectionKeyT, uri: URI, endpoint: HostnameEndpoint+ self, key: ConnectionKey, uri: URI, endpoint: HostnameEndpoint) -> Deferred[H2ClientProtocol]:self._pending_requests[key] = deque()@@ -83,7 +83,7 @@ class H2ConnectionPool:return ddef put_connection(- self, conn: H2ClientProtocol, key: ConnectionKeyT+ self, conn: H2ClientProtocol, key: ConnectionKey) -> H2ClientProtocol:self._connections[key] = conn@@ -96,7 +96,7 @@ class H2ConnectionPool:return conn- def _remove_connection(self, _: None, key: ConnectionKeyT) -> None:+ def _remove_connection(self, _: None, key: ConnectionKey) -> None:self._connections.pop(key)def close_connections(self) -> None:@@ -127,7 +127,7 @@ class H2Agent:def get_endpoint(self, uri: URI) -> HostnameEndpoint:return self.endpoint_factory.endpointForURI(uri) # type: ignore[no-any-return]- def get_key(self, uri: URI) -> ConnectionKeyT:+ def get_key(self, uri: URI) -> ConnectionKey:"""Arguments:uri - URI obtained directly from request URLdiff --git a/scrapy/core/downloader/handlers/http11.py b/scrapy/core/downloader/handlers/http11.pyindex 42ebdaace..4cc7cf944 100644--- a/scrapy/core/downloader/handlers/http11.py+++ b/scrapy/core/downloader/handlers/http11.py@@ -797,8 +797,7 @@ class _LenientHTTPClientParser(HTTPClientParser):# a colon.# Handle the normal CR LF case.- if line[-1:] == b"\r":- line = line[:-1]+ line = line.removesuffix(b"\r")if self.state == STATUS:self.statusReceived(line) # type: ignore[no-untyped-call]diff --git a/scrapy/extensions/httpcache.py b/scrapy/extensions/httpcache.pyindex d8ef3e3cd..8e885d8d0 100644--- a/scrapy/extensions/httpcache.py+++ b/scrapy/extensions/httpcache.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport gzipimport loggingimport pickle-from email.utils import mktime_tz, parsedate_tz+from datetime import timezone+from email.utils import parsedate_to_datetimefrom importlib import import_modulefrom pathlib import Pathfrom time import time@@ -418,8 +419,17 @@ def parse_cachecontrol(header: bytes) -> dict[bytes, bytes | None]:def rfc1123_to_epoch(date_str: str | bytes | None) -> int | None:+ # The HTTP time format (which is how we use this function) is actually in+ # RFC 7231 §7.1.1.1, it refers to RFC 5322 and also requires support for+ # two obsolete formats (RFC 850 and asctime()). email.utils evidently+ # supports all three.+ if date_str is None:+ return Nonetry:- date_str = to_unicode(date_str, encoding="ascii") # type: ignore[arg-type]- return mktime_tz(parsedate_tz(date_str)) # type: ignore[arg-type]+ date_str = to_unicode(date_str, encoding="ascii")+ date = parsedate_to_datetime(date_str)+ if date.tzinfo is None:+ date = date.replace(tzinfo=timezone.utc)+ return int(date.timestamp())except Exception:return Nonediff --git a/scrapy/extensions/telnet.py b/scrapy/extensions/telnet.pyindex 392f79299..04eee35f5 100644--- a/scrapy/extensions/telnet.py+++ b/scrapy/extensions/telnet.py@@ -6,10 +6,9 @@ See documentation in docs/topics/telnetconsole.rstfrom __future__ import annotations-import binasciiimport logging-import osimport pprint+from secrets import token_hexfrom typing import TYPE_CHECKING, Anyfrom twisted.conch import telnet@@ -61,7 +60,7 @@ class TelnetConsole(protocol.ServerFactory):self.password: str = crawler.settings["TELNETCONSOLE_PASSWORD"]if not self.password:- self.password = binascii.hexlify(os.urandom(8)).decode("utf8")+ self.password = token_hex(8)logger.info("Telnet Password: %s", self.password)self.crawler.signals.connect(self.start_listening, signals.engine_started)diff --git a/scrapy/responsetypes.py b/scrapy/responsetypes.pyindex 29e9b6bb7..3d9dafda6 100644--- a/scrapy/responsetypes.py+++ b/scrapy/responsetypes.py@@ -5,9 +5,8 @@ based on different criteria.from __future__ import annotations-from io import StringIO+from importlib.resources import filesfrom mimetypes import MimeTypes-from pkgutil import get_datafrom typing import TYPE_CHECKING, ClassVarfrom scrapy.http import Response@@ -39,9 +38,8 @@ class ResponseTypes:def __init__(self) -> None:self.classes: dict[str, type[Response]] = {}self.mimetypes: MimeTypes = MimeTypes()- mimedata = get_data("scrapy", "mime.types")- assert mimedata is not None- self.mimetypes.readfp(StringIO(mimedata.decode("utf8")))+ with files("scrapy").joinpath("mime.types").open(encoding="utf8") as f:+ self.mimetypes.readfp(f)for mimetype, cls in self.CLASSES.items():self.classes[mimetype] = load_object(cls)diff --git a/scrapy/statscollectors.py b/scrapy/statscollectors.pyindex 1827c2230..b1ce467e9 100644--- a/scrapy/statscollectors.py+++ b/scrapy/statscollectors.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport loggingimport pprint-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, TypeAliasfrom scrapy.utils.decorators import _warn_spider_arg@@ -18,7 +18,7 @@ if TYPE_CHECKING:logger = logging.getLogger(__name__)-StatsT = dict[str, Any]+StatsT: TypeAlias = dict[str, Any]class StatsCollector:diff --git a/scrapy/utils/console.py b/scrapy/utils/console.pyindex 23b4401e8..27730e1a3 100644--- a/scrapy/utils/console.py+++ b/scrapy/utils/console.py@@ -4,13 +4,13 @@ import asyncioimport codefrom collections.abc import Callablefrom functools import partial, wraps-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, TypeAliasif TYPE_CHECKING:from collections.abc import Iterable-EmbedFuncT = Callable[..., None]-KnownShellsT = dict[str, Callable[..., EmbedFuncT]]+EmbedFuncT: TypeAlias = Callable[..., None]+KnownShellsT: TypeAlias = dict[str, Callable[..., EmbedFuncT]]def _embed_ipython_shell(diff --git a/scrapy/utils/defer.py b/scrapy/utils/defer.pyindex 2b5e3f702..584961379 100644--- a/scrapy/utils/defer.py+++ b/scrapy/utils/defer.py@@ -223,7 +223,7 @@ class _AsyncCooperatorAdapter(Iterator[Deferred[Any]], Generic[_T]):*callable_args: _P.args,**callable_kwargs: _P.kwargs,):- self.aiterator: AsyncIterator[_T] = aiterable.__aiter__()+ self.aiterator: AsyncIterator[_T] = aiter(aiterable)self.callable: Callable[Concatenate[_T, _P], Deferred[Any] | None] = callable_self.callable_args: tuple[Any, ...] = callable_argsself.callable_kwargs: dict[str, Any] = callable_kwargsdiff --git a/scrapy/utils/python.py b/scrapy/utils/python.pyindex 8485b06f3..fdc1f8f94 100644--- a/scrapy/utils/python.py+++ b/scrapy/utils/python.py@@ -363,7 +363,7 @@ class MutableAsyncChain(AsyncIterator[_T]):return selfasync def __anext__(self) -> _T:- return await self.data.__anext__()+ return await anext(self.data)def _looks_like_import_path(value: str) -> bool:diff --git a/tests/benchmarks/test_crawl.py b/tests/benchmarks/test_crawl.pyindex 8170361ef..7495c309f 100644--- a/tests/benchmarks/test_crawl.py+++ b/tests/benchmarks/test_crawl.py@@ -216,7 +216,7 @@ def _crawl_tree() -> Crawler:crawler = crawl(_TreeSpider,- {**NULL_SETTINGS, **settings},+ NULL_SETTINGS | settings,domains=domains,pages=pages,items=items,diff --git a/tests/test_downloadermiddleware_httpcache.py b/tests/test_downloadermiddleware_httpcache.pyindex 5a02e6861..f9986a849 100644--- a/tests/test_downloadermiddleware_httpcache.py+++ b/tests/test_downloadermiddleware_httpcache.py@@ -15,7 +15,7 @@ import pytestfrom scrapy.downloadermiddlewares.httpcache import HttpCacheMiddlewarefrom scrapy.exceptions import IgnoreRequest-from scrapy.extensions.httpcache import DummyPolicy+from scrapy.extensions.httpcache import DummyPolicy, rfc1123_to_epochfrom scrapy.http import HtmlResponse, Request, Responsefrom scrapy.spiders import Spiderfrom scrapy.utils.misc import build_from_crawler@@ -853,3 +853,18 @@ class TestFilesystemStorageGzipWithDummyPolicy(TestFilesystemStorageWithDummyPol# A spider killed while writing a gzip file leaves it truncated.body_path = Path(storage._get_request_path(spider, request), "response_body")body_path.write_bytes(body_path.read_bytes()[:-5])+++ ("string", "expected"),+ [+ # RFC examples+ ("Sun, 06 Nov 1994 08:49:37 GMT", 784111777),+ ("Sunday, 06-Nov-94 08:49:37 GMT", 784111777),+ ("Sun Nov 6 08:49:37 1994", 784111777),+ (None, None),+ ("foo", None),+ ],+)+def test_rfc1123_to_epoch(string: str | None, expected: int | None) -> None:+ assert rfc1123_to_epoch(string) == expecteddiff --git a/tests/test_utils_python.py b/tests/test_utils_python.pyindex 25e50960f..3e46dca18 100644--- a/tests/test_utils_python.py+++ b/tests/test_utils_python.py@@ -60,7 +60,7 @@ class TestMutableAsyncChain:m.extend(self.g2())m.extend(self.g3())- assert await m.__anext__() == 0+ assert await anext(m) == 0results = await collect_asyncgen(m)assert results == list(range(1, 10))diff --git a/tests/utils/bases/download_handlers_http.py b/tests/utils/bases/download_handlers_http.pyindex 51d27a31a..7b54ed21f 100644--- a/tests/utils/bases/download_handlers_http.py+++ b/tests/utils/bases/download_handlers_http.py@@ -1752,7 +1752,7 @@ class TestRealWebsiteBase(ABC):self, settings_dict: dict[str, Any] | None = None) -> AsyncGenerator[DownloadHandlerProtocol]:crawler = get_crawler(- DefaultSpider, {**REAL_WEBSITE_SETTINGS, **(settings_dict or {})}+ DefaultSpider, REAL_WEBSITE_SETTINGS | (settings_dict or {}))crawler.spider = crawler._create_spider()dh = build_from_crawler(self.download_handler_cls, crawler)@@ -1772,7 +1772,7 @@ class TestRealWebsiteBase(ABC):@coroutine_testasync def test_download_with_spider(self) -> None:crawler = get_crawler(- SingleRequestSpider, {**REAL_WEBSITE_SETTINGS, **(self.settings_dict or {})}+ SingleRequestSpider, REAL_WEBSITE_SETTINGS | (self.settings_dict or {}))await maybe_deferred_to_future(crawler.crawl(seed=Request("https://books.toscrape.com/"))diff --git a/tests/utils/bases/redirect.py b/tests/utils/bases/redirect.pyindex 485e674fa..63e271ec9 100644--- a/tests/utils/bases/redirect.py+++ b/tests/utils/bases/redirect.py@@ -122,7 +122,7 @@ class TestRedirectBase(ABC):original_request = Request("https://example.com",- headers={**safe_headers, **cookie_header, **authorization_header},+ headers=safe_headers | cookie_header | authorization_header,)# Redirects to the same origin (same scheme, same domain, same port)@@ -138,7 +138,7 @@ class TestRedirectBase(ABC):# keep all headers also when the scheme is http.http_request = Request("http://example.com",- headers={**safe_headers, **cookie_header, **authorization_header},+ headers=safe_headers | cookie_header | authorization_header,)http_response = self.get_response(http_request, "http://example.com/a")http_redirect_request = self.mw.process_response(http_request, http_response)