Bump black.

This commit is contained in:
Andrey Rakhmatullin 2024-02-27 19:49:06 +05:00
parent 415c47479f
commit 282767f23b
59 changed files with 102 additions and 60 deletions

View File

@ -1,7 +1,7 @@
[flake8] [flake8]
max-line-length = 119 max-line-length = 119
ignore = W503, E203 ignore = E203, E501, E701, E704, W503
exclude = exclude =
docs/conf.py docs/conf.py

View File

@ -9,7 +9,7 @@ repos:
hooks: hooks:
- id: flake8 - id: flake8
- repo: https://github.com/psf/black.git - repo: https://github.com/psf/black.git
rev: 23.9.1 rev: 24.2.0
hooks: hooks:
- id: black - id: black
- repo: https://github.com/pycqa/isort - repo: https://github.com/pycqa/isort
@ -21,4 +21,4 @@ repos:
hooks: hooks:
- id: blacken-docs - id: blacken-docs
additional_dependencies: additional_dependencies:
- black==23.9.1 - black==24.2.0

View File

@ -150,8 +150,7 @@ Access the crawler instance:
def from_crawler(cls, crawler): def from_crawler(cls, crawler):
return cls(crawler) return cls(crawler)
def update_settings(self, settings): def update_settings(self, settings): ...
...
Use a fallback component: Use a fallback component:

View File

@ -1,6 +1,7 @@
""" """
Base class for Scrapy commands Base class for Scrapy commands
""" """
import argparse import argparse
import os import os
from pathlib import Path from pathlib import Path

View File

@ -3,6 +3,7 @@ Scrapy Shell
See documentation in docs/topics/shell.rst See documentation in docs/topics/shell.rst
""" """
from argparse import Namespace from argparse import Namespace
from threading import Thread from threading import Thread
from typing import List, Type from typing import List, Type

View File

@ -21,9 +21,9 @@ logger = logging.getLogger(__name__)
class DownloadHandlers: class DownloadHandlers:
def __init__(self, crawler: "Crawler"): def __init__(self, crawler: "Crawler"):
self._crawler: "Crawler" = crawler self._crawler: "Crawler" = crawler
self._schemes: Dict[ self._schemes: Dict[str, Union[str, Callable]] = (
str, Union[str, Callable] {}
] = {} # stores acceptable schemes on instancing ) # stores acceptable schemes on instancing
self._handlers: Dict[str, Any] = {} # stores instanced handlers for schemes self._handlers: Dict[str, Any] = {} # stores instanced handlers for schemes
self._notconfigured: Dict[str, str] = {} # remembers failed handlers self._notconfigured: Dict[str, str] = {} # remembers failed handlers
handlers: Dict[str, Union[str, Callable]] = without_none_values( handlers: Dict[str, Union[str, Callable]] = without_none_values(

View File

@ -1,5 +1,6 @@
"""Download handlers for http and https schemes """Download handlers for http and https schemes
""" """
from scrapy.utils.misc import build_from_crawler, load_object from scrapy.utils.misc import build_from_crawler, load_object
from scrapy.utils.python import to_unicode from scrapy.utils.python import to_unicode

View File

@ -3,6 +3,7 @@ Downloader Middleware manager
See documentation in docs/topics/downloader-middleware.rst See documentation in docs/topics/downloader-middleware.rst
""" """
from typing import Any, Callable, Generator, List, Union, cast from typing import Any, Callable, Generator, List, Union, cast
from twisted.internet.defer import Deferred, inlineCallbacks from twisted.internet.defer import Deferred, inlineCallbacks

View File

@ -4,6 +4,7 @@ This is the Scrapy engine which controls the Scheduler, Downloader and Spider.
For more information see docs/topics/architecture.rst For more information see docs/topics/architecture.rst
""" """
import logging import logging
from time import time from time import time
from typing import ( from typing import (

View File

@ -111,17 +111,17 @@ class Stream:
# Metadata of an HTTP/2 connection stream # Metadata of an HTTP/2 connection stream
# initialized when stream is instantiated # initialized when stream is instantiated
self.metadata: Dict = { self.metadata: Dict = {
"request_content_length": 0 "request_content_length": (
if self._request.body is None 0 if self._request.body is None else len(self._request.body)
else len(self._request.body), ),
# Flag to keep track whether the stream has initiated the request # Flag to keep track whether the stream has initiated the request
"request_sent": False, "request_sent": False,
# Flag to track whether we have logged about exceeding download warnsize # Flag to track whether we have logged about exceeding download warnsize
"reached_warnsize": False, "reached_warnsize": False,
# Each time we send a data frame, we will decrease value by the amount send. # Each time we send a data frame, we will decrease value by the amount send.
"remaining_content_length": 0 "remaining_content_length": (
if self._request.body is None 0 if self._request.body is None else len(self._request.body)
else len(self._request.body), ),
# Flag to keep track whether client (self) have closed this stream # Flag to keep track whether client (self) have closed this stream
"stream_closed_local": False, "stream_closed_local": False,
# Flag to keep track whether the server has closed the stream # Flag to keep track whether the server has closed the stream

View File

@ -1,5 +1,6 @@
"""This module implements the Scraper component which parses responses and """This module implements the Scraper component which parses responses and
extracts information from them""" extracts information from them"""
from __future__ import annotations from __future__ import annotations
import logging import logging

View File

@ -3,6 +3,7 @@ Spider Middleware manager
See documentation in docs/topics/spider-middleware.rst See documentation in docs/topics/spider-middleware.rst
""" """
import logging import logging
from inspect import isasyncgenfunction, iscoroutine from inspect import isasyncgenfunction, iscoroutine
from itertools import islice from itertools import islice

View File

@ -3,6 +3,7 @@ DefaultHeaders downloader middleware
See documentation in docs/topics/downloader-middleware.rst See documentation in docs/topics/downloader-middleware.rst
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Iterable, Tuple, Union from typing import TYPE_CHECKING, Iterable, Tuple, Union

View File

@ -3,6 +3,7 @@ Download timeout middleware
See documentation in docs/topics/downloader-middleware.rst See documentation in docs/topics/downloader-middleware.rst
""" """
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING, Union from typing import TYPE_CHECKING, Union

View File

@ -9,6 +9,7 @@ RETRY_HTTP_CODES - which HTTP response codes to retry
Failed pages are collected on the scraping process and rescheduled at the end, Failed pages are collected on the scraping process and rescheduled at the end,
once the spider has finished crawling all regular (non failed) pages. once the spider has finished crawling all regular (non failed) pages.
""" """
from __future__ import annotations from __future__ import annotations
import warnings import warnings

View File

@ -4,6 +4,7 @@ Scrapy core exceptions
These exceptions are documented in docs/topics/exceptions.rst. Please don't add These exceptions are documented in docs/topics/exceptions.rst. Please don't add
new exceptions here without documenting them there. new exceptions here without documenting them there.
""" """
from typing import Any from typing import Any
# Internal # Internal

View File

@ -3,6 +3,7 @@ The Extension Manager
See documentation in docs/topics/extensions.rst See documentation in docs/topics/extensions.rst
""" """
from scrapy.middleware import MiddlewareManager from scrapy.middleware import MiddlewareManager
from scrapy.utils.conf import build_component_list from scrapy.utils.conf import build_component_list

View File

@ -1,6 +1,7 @@
""" """
Extension for collecting core stats like items scraped and start/finish times Extension for collecting core stats like items scraped and start/finish times
""" """
from datetime import datetime, timezone from datetime import datetime, timezone
from scrapy import signals from scrapy import signals

View File

@ -3,6 +3,7 @@ MemoryUsage extension
See documentation in docs/topics/extensions.rst See documentation in docs/topics/extensions.rst
""" """
import logging import logging
import socket import socket
import sys import sys

View File

@ -1,6 +1,7 @@
""" """
Extension for processing data before they are exported to feeds. Extension for processing data before they are exported to feeds.
""" """
from bz2 import BZ2File from bz2 import BZ2File
from gzip import GzipFile from gzip import GzipFile
from io import IOBase from io import IOBase

View File

@ -4,6 +4,7 @@ requests in Scrapy.
See documentation in docs/topics/request-response.rst See documentation in docs/topics/request-response.rst
""" """
import inspect import inspect
from typing import ( from typing import (
Any, Any,
@ -231,12 +232,16 @@ class Request(object_ref):
""" """
d = { d = {
"url": self.url, # urls are safe (safe_string_url) "url": self.url, # urls are safe (safe_string_url)
"callback": _find_method(spider, self.callback) "callback": (
if callable(self.callback) _find_method(spider, self.callback)
else self.callback, if callable(self.callback)
"errback": _find_method(spider, self.errback) else self.callback
if callable(self.errback) ),
else self.errback, "errback": (
_find_method(spider, self.errback)
if callable(self.errback)
else self.errback
),
"headers": dict(self.headers), "headers": dict(self.headers),
} }
for attr in self.attributes: for attr in self.attributes:

View File

@ -4,6 +4,7 @@ This module implements the XmlRpcRequest class which is a more convenient class
See documentation in docs/topics/request-response.rst See documentation in docs/topics/request-response.rst
""" """
import xmlrpc.client as xmlrpclib import xmlrpc.client as xmlrpclib
from typing import Any, Optional from typing import Any, Optional

View File

@ -4,6 +4,7 @@ responses in Scrapy.
See documentation in docs/topics/request-response.rst See documentation in docs/topics/request-response.rst
""" """
from __future__ import annotations from __future__ import annotations
from ipaddress import IPv4Address, IPv6Address from ipaddress import IPv4Address, IPv6Address

View File

@ -4,6 +4,7 @@ discovering (through HTTP headers) to base Response class.
See documentation in docs/topics/request-response.rst See documentation in docs/topics/request-response.rst
""" """
from __future__ import annotations from __future__ import annotations
import json import json

View File

@ -4,6 +4,7 @@ This module defines the Link object used in Link extractors.
For actual link extractors implementation see scrapy.linkextractors, or For actual link extractors implementation see scrapy.linkextractors, or
its documentation in: docs/topics/link-extractors.rst its documentation in: docs/topics/link-extractors.rst
""" """
from typing import Any from typing import Any

View File

@ -5,6 +5,7 @@ This package contains a collection of Link Extractors.
For more info see docs/topics/link-extractors.rst For more info see docs/topics/link-extractors.rst
""" """
import re import re
# common file extensions that are not followed if they occur in links # common file extensions that are not followed if they occur in links

View File

@ -1,6 +1,7 @@
""" """
Link extractor based on lxml.html Link extractor based on lxml.html
""" """
import logging import logging
import operator import operator
from functools import partial from functools import partial

View File

@ -3,6 +3,7 @@ Item Loader
See documentation in docs/topics/loaders.rst See documentation in docs/topics/loaders.rst
""" """
import itemloaders import itemloaders
from scrapy.item import Item from scrapy.item import Item

View File

@ -3,6 +3,7 @@ Mail sending helpers
See documentation in docs/topics/email.rst See documentation in docs/topics/email.rst
""" """
import logging import logging
from email import encoders as Encoders from email import encoders as Encoders
from email.mime.base import MIMEBase from email.mime.base import MIMEBase

View File

@ -3,6 +3,7 @@ Item pipeline
See documentation in docs/item-pipeline.rst See documentation in docs/item-pipeline.rst
""" """
from typing import Any, List from typing import Any, List
from twisted.internet.defer import Deferred from twisted.internet.defer import Deferred

View File

@ -3,6 +3,7 @@ Files Pipeline
See documentation in topics/media-pipeline.rst See documentation in topics/media-pipeline.rst
""" """
import base64 import base64
import functools import functools
import hashlib import hashlib

View File

@ -3,6 +3,7 @@ Images Pipeline
See documentation in topics/media-pipeline.rst See documentation in topics/media-pipeline.rst
""" """
import functools import functools
import hashlib import hashlib
import warnings import warnings

View File

@ -2,6 +2,7 @@
This module implements a class which returns the appropriate Response class This module implements a class which returns the appropriate Response class
based on different criteria. based on different criteria.
""" """
from io import StringIO from io import StringIO
from mimetypes import MimeTypes from mimetypes import MimeTypes
from pkgutil import get_data from pkgutil import get_data

View File

@ -1,6 +1,7 @@
""" """
XPath selectors based on lxml XPath selectors based on lxml
""" """
from typing import Any, Optional, Type, Union from typing import Any, Optional, Type, Union
from parsel import Selector as _ParselSelector from parsel import Selector as _ParselSelector

View File

@ -58,7 +58,6 @@ def get_settings_priority(priority: Union[int, str]) -> int:
class SettingsAttribute: class SettingsAttribute:
"""Class for storing data related to settings attributes. """Class for storing data related to settings attributes.
This class is intended for internal usage, you should try Settings class This class is intended for internal usage, you should try Settings class

View File

@ -3,6 +3,7 @@
See documentation in docs/topics/shell.rst See documentation in docs/topics/shell.rst
""" """
import os import os
import signal import signal

View File

@ -3,6 +3,7 @@ HttpError Spider Middleware
See documentation in docs/topics/spider-middleware.rst See documentation in docs/topics/spider-middleware.rst
""" """
from __future__ import annotations from __future__ import annotations
import logging import logging

View File

@ -3,6 +3,7 @@ Offsite Spider Middleware
See documentation in docs/topics/spider-middleware.rst See documentation in docs/topics/spider-middleware.rst
""" """
from __future__ import annotations from __future__ import annotations
import logging import logging

View File

@ -2,6 +2,7 @@
RefererMiddleware: populates Request referer field, based on the Response which RefererMiddleware: populates Request referer field, based on the Response which
originated it. originated it.
""" """
from __future__ import annotations from __future__ import annotations
import warnings import warnings

View File

@ -3,6 +3,7 @@ Base class for Scrapy spiders
See documentation in docs/topics/spiders.rst See documentation in docs/topics/spiders.rst
""" """
from __future__ import annotations from __future__ import annotations
import logging import logging

View File

@ -4,6 +4,7 @@ for scraping from an XML feed.
See documentation in docs/topics/spiders.rst See documentation in docs/topics/spiders.rst
""" """
from scrapy.exceptions import NotConfigured, NotSupported from scrapy.exceptions import NotConfigured, NotSupported
from scrapy.selector import Selector from scrapy.selector import Selector
from scrapy.spiders import Spider from scrapy.spiders import Spider

View File

@ -1,6 +1,7 @@
""" """
Scrapy extension for collecting scraping stats Scrapy extension for collecting scraping stats
""" """
import logging import logging
import pprint import pprint
from typing import TYPE_CHECKING, Any, Dict, Optional from typing import TYPE_CHECKING, Any, Dict, Optional

View File

@ -1,6 +1,7 @@
""" """
Helper functions for dealing with Twisted deferreds Helper functions for dealing with Twisted deferreds
""" """
import asyncio import asyncio
import inspect import inspect
from asyncio import Future from asyncio import Future
@ -304,13 +305,11 @@ _T = TypeVar("_T")
@overload @overload
def deferred_from_coro(o: _CT) -> Deferred: def deferred_from_coro(o: _CT) -> Deferred: ...
...
@overload @overload
def deferred_from_coro(o: _T) -> _T: def deferred_from_coro(o: _T) -> _T: ...
...
def deferred_from_coro(o: _T) -> Union[Deferred, _T]: def deferred_from_coro(o: _T) -> Union[Deferred, _T]:

View File

@ -138,13 +138,11 @@ DEPRECATION_RULES: List[Tuple[str, str]] = []
@overload @overload
def update_classpath(path: str) -> str: def update_classpath(path: str) -> str: ...
...
@overload @overload
def update_classpath(path: Any) -> Any: def update_classpath(path: Any) -> Any: ...
...
def update_classpath(path: Any) -> Any: def update_classpath(path: Any) -> Any:

View File

@ -225,18 +225,17 @@ def csviter(
@overload @overload
def _body_or_str(obj: Union[Response, str, bytes]) -> str: def _body_or_str(obj: Union[Response, str, bytes]) -> str: ...
...
@overload @overload
def _body_or_str(obj: Union[Response, str, bytes], unicode: Literal[True]) -> str: def _body_or_str(obj: Union[Response, str, bytes], unicode: Literal[True]) -> str: ...
...
@overload @overload
def _body_or_str(obj: Union[Response, str, bytes], unicode: Literal[False]) -> bytes: def _body_or_str(
... obj: Union[Response, str, bytes], unicode: Literal[False]
) -> bytes: ...
def _body_or_str( def _body_or_str(

View File

@ -1,4 +1,5 @@
"""Helper functions which don't fit anywhere else""" """Helper functions which don't fit anywhere else"""
import ast import ast
import hashlib import hashlib
import inspect import inspect

View File

@ -1,6 +1,7 @@
""" """
This module contains essential stuff that should've come with Python itself ;) This module contains essential stuff that should've come with Python itself ;)
""" """
import collections.abc import collections.abc
import gc import gc
import inspect import inspect
@ -285,13 +286,11 @@ def equal_attributes(
@overload @overload
def without_none_values(iterable: Mapping) -> dict: def without_none_values(iterable: Mapping) -> dict: ...
...
@overload @overload
def without_none_values(iterable: Iterable) -> Iterable: def without_none_values(iterable: Iterable) -> Iterable: ...
...
def without_none_values(iterable: Union[Mapping, Iterable]) -> Union[dict, Iterable]: def without_none_values(iterable: Union[Mapping, Iterable]) -> Union[dict, Iterable]:

View File

@ -44,7 +44,9 @@ def _serialize_headers(
yield from request.headers.getlist(header) yield from request.headers.getlist(header)
_fingerprint_cache: "WeakKeyDictionary[Request, Dict[Tuple[Optional[Tuple[bytes, ...]], bool], bytes]]" _fingerprint_cache: (
"WeakKeyDictionary[Request, Dict[Tuple[Optional[Tuple[bytes, ...]], bool], bytes]]"
)
_fingerprint_cache = WeakKeyDictionary() _fingerprint_cache = WeakKeyDictionary()
@ -114,8 +116,7 @@ def fingerprint(
class RequestFingerprinterProtocol(Protocol): class RequestFingerprinterProtocol(Protocol):
def fingerprint(self, request: Request) -> bytes: def fingerprint(self, request: Request) -> bytes: ...
...
class RequestFingerprinter: class RequestFingerprinter:

View File

@ -2,6 +2,7 @@
This module provides some useful functions for working with This module provides some useful functions for working with
scrapy.http.Response objects scrapy.http.Response objects
""" """
import os import os
import re import re
import tempfile import tempfile
@ -29,9 +30,9 @@ def get_base_url(response: "scrapy.http.response.text.TextResponse") -> str:
return _baseurl_cache[response] return _baseurl_cache[response]
_metaref_cache: "WeakKeyDictionary[Response, Union[Tuple[None, None], Tuple[float, str]]]" = ( _metaref_cache: (
WeakKeyDictionary() "WeakKeyDictionary[Response, Union[Tuple[None, None], Tuple[float, str]]]"
) ) = WeakKeyDictionary()
def get_meta_refresh( def get_meta_refresh(

View File

@ -1,4 +1,5 @@
"""Helper functions for working with signals""" """Helper functions for working with signals"""
import collections.abc import collections.abc
import logging import logging
from typing import Any as TypingAny from typing import Any as TypingAny

View File

@ -4,6 +4,7 @@ Module for processing Sitemaps.
Note: The main purpose of this module is to provide support for the Note: The main purpose of this module is to provide support for the
SitemapSpider, its API is subject to change without notice. SitemapSpider, its API is subject to change without notice.
""" """
from typing import Any, Dict, Generator, Iterator, Optional from typing import Any, Dict, Generator, Iterator, Optional
from urllib.parse import urljoin from urllib.parse import urljoin

View File

@ -39,13 +39,11 @@ def iterate_spider_output(result: AsyncGenerator) -> AsyncGenerator: # type: ig
@overload @overload
def iterate_spider_output(result: CoroutineType) -> Deferred: def iterate_spider_output(result: CoroutineType) -> Deferred: ...
...
@overload @overload
def iterate_spider_output(result: _T) -> Iterable: def iterate_spider_output(result: _T) -> Iterable: ...
...
def iterate_spider_output(result: Any) -> Union[Iterable, AsyncGenerator, Deferred]: def iterate_spider_output(result: Any) -> Union[Iterable, AsyncGenerator, Deferred]:
@ -83,8 +81,7 @@ def spidercls_for_request(
default_spidercls: Type[Spider], default_spidercls: Type[Spider],
log_none: bool = ..., log_none: bool = ...,
log_multiple: bool = ..., log_multiple: bool = ...,
) -> Type[Spider]: ) -> Type[Spider]: ...
...
@overload @overload
@ -94,8 +91,7 @@ def spidercls_for_request(
default_spidercls: Literal[None], default_spidercls: Literal[None],
log_none: bool = ..., log_none: bool = ...,
log_multiple: bool = ..., log_multiple: bool = ...,
) -> Optional[Type[Spider]]: ) -> Optional[Type[Spider]]: ...
...
@overload @overload
@ -105,8 +101,7 @@ def spidercls_for_request(
*, *,
log_none: bool = ..., log_none: bool = ...,
log_multiple: bool = ..., log_multiple: bool = ...,
) -> Optional[Type[Spider]]: ) -> Optional[Type[Spider]]: ...
...
def spidercls_for_request( def spidercls_for_request(

View File

@ -5,6 +5,7 @@ library.
Some of the functions that used to be imported from this module have been moved Some of the functions that used to be imported from this module have been moved
to the w3lib.url module. Always import those from there instead. to the w3lib.url module. Always import those from there instead.
""" """
import re import re
from typing import TYPE_CHECKING, Iterable, Optional, Type, Union, cast from typing import TYPE_CHECKING, Iterable, Optional, Type, Union, cast
from urllib.parse import ParseResult, urldefrag, urlparse, urlunparse from urllib.parse import ParseResult, urldefrag, urlparse, urlunparse

View File

@ -1,4 +1,5 @@
"""DBM-like dummy module""" """DBM-like dummy module"""
import collections import collections
from typing import Any, DefaultDict from typing import Any, DefaultDict

View File

@ -1,6 +1,7 @@
""" """
Some spiders used for testing and benchmarking Some spiders used for testing and benchmarking
""" """
import asyncio import asyncio
import time import time
from urllib.parse import urlencode from urllib.parse import urlencode

View File

@ -121,7 +121,9 @@ class BaseItemExporterTest(unittest.TestCase):
self.assertEqual(name, "John\xa3") self.assertEqual(name, "John\xa3")
ie = self._get_exporter(fields_to_export={"name": "名稱"}) ie = self._get_exporter(fields_to_export={"name": "名稱"})
self.assertEqual(list(ie._get_serialized_fields(self.i)), [("名稱", "John\xa3")]) self.assertEqual(
list(ie._get_serialized_fields(self.i)), [("名稱", "John\xa3")]
)
def test_field_custom_serializer(self): def test_field_custom_serializer(self):
i = self.custom_field_item_class(name="John\xa3", age="22") i = self.custom_field_item_class(name="John\xa3", age="22")

View File

@ -22,9 +22,9 @@ from scrapy.utils.test import get_crawler
try: try:
from PIL import Image # noqa: imported just to check for the import error from PIL import Image # noqa: imported just to check for the import error
except ImportError: except ImportError:
skip_pillow: Optional[ skip_pillow: Optional[str] = (
str "Missing Python Imaging Library, install https://pypi.python.org/pypi/Pillow"
] = "Missing Python Imaging Library, install https://pypi.python.org/pypi/Pillow" )
else: else:
skip_pillow = None skip_pillow = None

View File

@ -33,7 +33,10 @@ class ResponseTypesTest(unittest.TestCase):
("attachment;filename=dataµ.tar.gz".encode("latin-1"), Response), ("attachment;filename=dataµ.tar.gz".encode("latin-1"), Response),
("attachment;filename=data高.doc".encode("gbk"), Response), ("attachment;filename=data高.doc".encode("gbk"), Response),
("attachment;filename=دورهdata.html".encode("cp720"), HtmlResponse), ("attachment;filename=دورهdata.html".encode("cp720"), HtmlResponse),
("attachment;filename=日本語版Wikipedia.xml".encode("iso2022_jp"), XmlResponse), (
"attachment;filename=日本語版Wikipedia.xml".encode("iso2022_jp"),
XmlResponse,
),
] ]
for source, cls in mappings: for source, cls in mappings:
retcls = responsetypes.from_content_disposition(source) retcls = responsetypes.from_content_disposition(source)

View File

@ -2,6 +2,7 @@
from twisted.internet import defer from twisted.internet import defer
Tests borrowed from the twisted.web.client tests. Tests borrowed from the twisted.web.client tests.
""" """
import shutil import shutil
from pathlib import Path from pathlib import Path
from tempfile import mkdtemp from tempfile import mkdtemp