Scrapy, a fast high-level web crawling & scraping framework for Python.
Merge remote-tracking branch 'origin/master' into asyncio-parse-asyncgen-proper-rebased
Andrey Rakhmatullinffc6f525cead
diff --cc scrapy/core/scraper.pyindex 7eedbf33e,c760a4155..8ce57af2f--- a/scrapy/core/scraper.py+++ b/scrapy/core/scraper.py@@@ -1,8 -1,10 +1,10 @@@"""This module implements the Scraper component which parses responses andextracts information from them"""-+import collectionsimport loggingfrom collections import deque+ from collections.abc import Iterable+ from typing import Unionfrom itemadapter import is_itemfrom twisted.internet import defer@@@ -185,17 -177,12 +185,17 @@@ class Scraperspider=spider)- def handle_spider_output(self, result, request, response, spider):+ def handle_spider_output(self, result: Iterable, request: Request, response: Response, spider: Spider):if not result:return defer_succeed(None)- it = iter_errback(result, self.handle_spider_error, request, response, spider)- dfd = parallel(it, self.concurrent_items, self._process_spidermw_output,- request, response, spider)+ if isinstance(result, collections.abc.AsyncIterable):+ it = aiter_errback(result, self.handle_spider_error, request, response, spider)+ dfd = parallel_async(it, self.concurrent_items, self._process_spidermw_output,+ request, response, spider)+ else:+ it = iter_errback(result, self.handle_spider_error, request, response, spider)+ dfd = parallel(it, self.concurrent_items, self._process_spidermw_output,+ request, response, spider)return dfddef _process_spidermw_output(self, output, request, response, spider):diff --cc scrapy/core/spidermw.pyindex d0d292007,7e58521ac..6fcbc7492--- a/scrapy/core/spidermw.py+++ b/scrapy/core/spidermw.py@@@ -3,21 -3,26 +3,28 @@@ Spider Middleware manageSee documentation in docs/topics/spider-middleware.rst"""+import collections.abcfrom itertools import islice-from typing import Any, Callable, Generator, Iterable, Union++from typing import Any, Callable, Generator, Iterable, Union, AsyncIterable+ from twisted.internet.defer import Deferredfrom twisted.python.failure import Failure+ from scrapy import Request, Spiderfrom scrapy.exceptions import _InvalidOutput+ from scrapy.http import Responsefrom scrapy.middleware import MiddlewareManager+from scrapy.utils.asyncgen import _process_iterable_universalfrom scrapy.utils.conf import build_component_listfrom scrapy.utils.defer import mustbe_deferred-from scrapy.utils.python import MutableChain+from scrapy.utils.python import MutableAsyncChain, MutableChain- def _isiterable(possible_iterator):- return hasattr(possible_iterator, '__iter__') or hasattr(possible_iterator, '__aiter__')+ ScrapeFunc = Callable[[Union[Response, Failure], Request, Spider], Any]+++ def _isiterable(o) -> bool:- return isinstance(o, Iterable)++ return isinstance(o, (Iterable, AsyncIterable))class SpiderMiddlewareManager(MiddlewareManager):@@@ -53,21 -59,20 +61,23 @@@return scrape_func(Failure(), request, spider)return scrape_func(response, request, spider)- def _evaluate_iterable(self, response, spider, iterable, exception_processor_index, recover_to):+ def _evaluate_iterable(self, response: Response, spider: Spider, iterable: Iterable,+ exception_processor_index: int, recover_to: MutableChain) -> Generator:- try:- for r in iterable:- yield r- except Exception as ex:- exception_result = self._process_spider_exception(response, spider, Failure(ex),- exception_processor_index)- if isinstance(exception_result, Failure):- raise- recover_to.extend(exception_result)+ @_process_iterable_universal+ async def _evaluate_async_iterable(iterable):+ try:+ async for r in iterable:+ yield r+ except Exception as ex:+ exception_result = self._process_spider_exception(response, spider, Failure(ex),+ exception_processor_index)+ if isinstance(exception_result, Failure):+ raise+ recover_to.extend(exception_result)+ return _evaluate_async_iterable(iterable)- def _process_spider_exception(self, response, spider, _failure, start_index=0):+ def _process_spider_exception(self, response: Response, spider: Spider, _failure: Failure,+ start_index: int = 0) -> Union[Failure, MutableChain]:exception = _failure.value# don't handle _InvalidOutput exceptionif isinstance(exception, _InvalidOutput):@@@ -89,14 -94,11 +99,15 @@@raise _InvalidOutput(msg)return _failure- def _process_spider_output(self, response, spider, result, start_index=0):+ def _process_spider_output(self, response: Response, spider: Spider,+ result: Iterable, start_index: int = 0) -> MutableChain:# items in this iterable do not need to go through the process_spider_output# chain, they went through it already from the process_spider_exception method- recovered = MutableChain()+ last_result_async = isinstance(result, collections.abc.AsyncIterator)+ if last_result_async:+ recovered = MutableAsyncChain()+ else:+ recovered = MutableChain()method_list = islice(self.methods['process_spider_output'], start_index, None)for method_index, method in enumerate(method_list, start=start_index):@@@ -116,32 -118,20 +127,33 @@@msg = (f"Middleware {method.__qualname__} must return an "f"iterable, got {type(result)}")raise _InvalidOutput(msg)+ if last_result_async and isinstance(result, collections.abc.Iterator):+ raise TypeError(f"Synchronous {method.__qualname__} called with an async iterable")+ last_result_async = isinstance(result, collections.abc.AsyncIterator)- return MutableChain(result, recovered)+ if last_result_async:+ return MutableAsyncChain(result, recovered)+ else:+ return MutableChain(result, recovered)- def _process_callback_output(self, response, spider, result):+ def _process_callback_output(self, response: Response, spider: Spider, result: Iterable) -> MutableChain:- recovered = MutableChain()+ if isinstance(result, collections.abc.AsyncIterator):+ recovered = MutableAsyncChain()+ else:+ recovered = MutableChain()result = self._evaluate_iterable(response, spider, result, 0, recovered)- return MutableChain(self._process_spider_output(response, spider, result), recovered)+ result = self._process_spider_output(response, spider, result)+ if isinstance(result, collections.abc.AsyncIterator):+ return MutableAsyncChain(result, recovered)+ else:+ return MutableChain(result, recovered)- def scrape_response(self, scrape_func, response, request, spider):- def process_callback_output(result):+ def scrape_response(self, scrape_func: ScrapeFunc, response: Response, request: Request,+ spider: Spider) -> Deferred:+ def process_callback_output(result: Iterable) -> MutableChain:return self._process_callback_output(response, spider, result)- def process_spider_exception(_failure):+ def process_spider_exception(_failure: Failure) -> Union[Failure, MutableChain]:return self._process_spider_exception(response, spider, _failure)dfd = mustbe_deferred(self._process_spider_input, scrape_func, response, request, spider)diff --cc scrapy/spidermiddlewares/referer.pyindex 8d862d1d0,608c0eea5..e0a22592f--- a/scrapy/spidermiddlewares/referer.py+++ b/scrapy/spidermiddlewares/referer.py@@@ -7,12 -8,11 +8,12 @@@ from urllib.parse import urlparsfrom w3lib.url import safe_url_string- from scrapy.http import Request, Response- from scrapy.exceptions import NotConfiguredfrom scrapy import signals+ from scrapy.exceptions import NotConfigured+ from scrapy.http import Request, Response+from scrapy.utils.asyncgen import _process_iterable_universal- from scrapy.utils.python import to_unicodefrom scrapy.utils.misc import load_object+ from scrapy.utils.python import to_unicodefrom scrapy.utils.url import strip_urldiff --cc scrapy/utils/asyncgen.pyindex 6c0bb1d10,c290e376c..92118ddb9--- a/scrapy/utils/asyncgen.py+++ b/scrapy/utils/asyncgen.py@@@ -1,9 -1,7 +1,10 @@@+import collections+import functools+import inspect+ from collections.abc import AsyncIterable- async def collect_asyncgen(result):+ async def collect_asyncgen(result: AsyncIterable):results = []async for x in result:results.append(x)diff --cc scrapy/utils/defer.pyindex ca3d79fa6,b317c12a3..f81faf6dd--- a/scrapy/utils/defer.py+++ b/scrapy/utils/defer.py@@@ -70,117 -75,14 +75,117 @@@ def parallel(iterable: Iterable, countTaken from: https://jcalderone.livejournal.com/24285.html"""- coop = task.Cooperator()+ coop = Cooperator()work = (callable(elem, *args, **named) for elem in iterable)- return defer.DeferredList([coop.coiterate(work) for _ in range(count)])+ return DeferredList([coop.coiterate(work) for _ in range(count)])+class _AsyncCooperatorAdapter:+ """ A class that wraps an async iterator into a normal iterator suitable+ for using in Cooperator.coiterate(). As it's only needed for parallel_async(),+ it calls the callable directly in the callback, instead of providing a more+ generic interface.++ On the outside, this class behaves as an iterator that yields Deferreds.+ Each Deferred is fired with the result of the callable which was called on+ the next result from aiterator. It raises StopIteration when aiterator is+ exhausted, as expected.++ Cooperator calls __next__() multiple times and waits on the Deferreds+ returned from it. As async generators (since Python 3.8) don't support+ awaiting on __anext__() several times in parallel, we need to serialize+ this. It's done by storing the Deferreds returned from __next__() and+ firing the oldest one when a result from __anext__() is available.++ The workflow:+ 1. When __next__() is called for the first time, it creates a Deferred, stores it+ in self.waiting_deferreds and returns it. It also makes a Deferred that will wait+ for self.aiterator.__anext__() and puts it into self.anext_deferred.+ 2. If __next__() is called again before self.anext_deferred fires, more Deferreds+ are added to self.waiting_deferreds.+ 3. When self.anext_deferred fires, it either calls _callback() or _errback(). Both+ clear self.anext_deferred.+ 3.1. _callback() calls the callable passing the result value that it takes, pops a+ Deferred from self.waiting_deferreds, and if the callable result was a Deferred, it+ chains those Deferreds so that the waiting Deferred will fire when the result+ Deferred does, otherwise it fires it directly. This causes one awaiting task to+ receive a result. If self.waiting_deferreds is still not empty, new __anext__() is+ called and self.anext_deferred is populated.+ 3.2. _errback() checks the exception class. If it's StopAsyncIteration it means+ self.aiterator is exhausted and so it sets self.finished and fires all+ self.waiting_deferreds. Other exceptions are propagated.+ 4. If __next__() is called after __anext__() was handled, then if self.finished is+ True, it raises StopIteration, otherwise it acts like in step 2, but if+ self.anext_deferred is now empty is also populates it with a new __anext__().++ Note that CooperativeTask ignores the value returned from the Deferred that it waits+ for, so we fire them with None when needed.++ It may be possible to write an async iterator-aware replacement for+ Cooperator/CooperativeTask and use it instead of this adapter to achieve the same+ goal.+ """+ def __init__(self, aiterator, callable, *callable_args, **callable_kwargs):+ self.aiterator = aiterator+ self.callable = callable+ self.callable_args = callable_args+ self.callable_kwargs = callable_kwargs+ self.finished = False+ self.waiting_deferreds = []+ self.anext_deferred = None++ def _callback(self, result):+ # This gets called when the result from aiterator.__anext__() is available.+ # It calls the callable on it and sends the result to the oldest waiting Deferred+ # (by chaining if the result is a Deferred too or by firing if not).+ self.anext_deferred = None+ result = self.callable(result, *self.callable_args, **self.callable_kwargs)+ d = self.waiting_deferreds.pop(0)+ if isinstance(result, defer.Deferred):+ result.chainDeferred(d)+ else:+ d.callback(None)+ if self.waiting_deferreds:+ self._call_anext()++ def _errback(self, failure):+ # This gets called on any exceptions in aiterator.__anext__().+ # It handles StopAsyncIteration by stopping the iteration and reraises all others.+ self.anext_deferred = None+ failure.trap(StopAsyncIteration)+ self.finished = True+ for d in self.waiting_deferreds:+ d.callback(None)++ def _call_anext(self):+ # This starts waiting for the next result from aiterator.+ # If aiterator is exhausted, _errback will be called.+ self.anext_deferred = deferred_from_coro(self.aiterator.__anext__())+ self.anext_deferred.addCallbacks(self._callback, self._errback)++ def __next__(self):+ # This puts a new Deferred into self.waiting_deferreds and returns it.+ # It also calls __anext__() if needed.+ if self.finished:+ raise StopIteration+ d = defer.Deferred()+ self.waiting_deferreds.append(d)+ if not self.anext_deferred:+ self._call_anext()+ return d+++def parallel_async(async_iterable, count, callable, *args, **named):+ """ Like parallel but for async iterables """- coop = task.Cooperator()++ coop = Cooperator()+ work = _AsyncCooperatorAdapter(async_iterable, callable, *args, **named)+ dl = defer.DeferredList([coop.coiterate(work) for _ in range(count)])+ return dl++- def process_chain(callbacks, input, *a, **kw):+ def process_chain(callbacks: Iterable[Callable], input, *a, **kw) -> Deferred:"""Return a Deferred built by chaining the given callbacks"""- d = defer.Deferred()+ d = Deferred()for x in callbacks:d.addCallback(x, *a, **kw)d.callback(input)@@@ -227,23 -129,9 +232,23 @@@ def iter_errback(iterable: Iterable, ererrback(failure.Failure(), *a, **kw)+async def aiter_errback(aiterable, errback, *a, **kw):+ """Wraps an async iterable calling an errback if an error is caught while+ iterating it. Similar to scrapy.utils.defer.iter_errback()+ """+ it = aiterable.__aiter__()+ while True:+ try:+ yield await it.__anext__()+ except StopAsyncIteration:+ break+ except Exception:+ errback(failure.Failure(), *a, **kw)++- def deferred_from_coro(o):+ def deferred_from_coro(o) -> Any:"""Converts a coroutine into a Deferred, or returns the object as is if it isn't a coroutine"""- if isinstance(o, defer.Deferred):+ if isinstance(o, Deferred):return oif asyncio.isfuture(o) or inspect.isawaitable(o):if not is_asyncio_reactor_installed():