asyncio

2.0 新版功能.

SCrapy部分支持 asyncio 。您先 install the asyncio reactor ,您可以使用 asyncioasyncio -支持的库位于任何 coroutine

警告

asyncio Scrapy中的支持是试验性的,尚未推荐用于生产环境。未来的Scrapy版本可能会引入相关更改,而不会出现弃用期限或警告。

安装异步电抗器

使能 asyncio 支持,设置 TWISTED_REACTOR 设置为 'twisted.internet.asyncioreactor.AsyncioSelectorReactor' .

如果您正在使用 CrawlerRunner ,您还需要安装 AsyncioSelectorReactor 反应堆手动。你可以用 install_reactor() ::

install_reactor('twisted.internet.asyncioreactor.AsyncioSelectorReactor')

使用自定义异步循环

您还可以将自定义异步事件循环与asyncio reactor一起使用。设置 ASYNCIO_EVENT_LOOP 设置为所需事件循环类的导入路径以使用它而不是默认的异步事件循环。

等待延期

当异步反应堆没有安装时,您可以直接在协程中等待Deferred。安装后,由于scrapy协程集成的特定要求(协程被包装到 asyncio.Future 对象,而不是放入 Deferred 直接),您需要将它们包装到期货中。Scrapy为此提供了两个帮助器:

scrapy.utils.defer.deferred_to_future(d: twisted.internet.defer.Deferred) _asyncio.Future[源代码]

VERSION 新版功能.

返回一个 asyncio.Future 包装的对象 d

什么时候 using the asyncio reactor ,你不能等待 Deferred 来自以下位置的对象 Scrapy callables defined as coroutines ,你只能等待 Future 对象。包装 Deferred 将对象放入 Future 对象允许您等待它们::

class MySpider(Spider):
    ...
    async def parse(self, response):
        d = treq.get('https://example.com/additional')
        additional_response = await deferred_to_future(d)
scrapy.utils.defer.maybe_deferred_to_future(d: twisted.internet.defer.Deferred) Union[twisted.internet.defer.Deferred, _asyncio.Future][源代码]

VERSION 新版功能.

返回 d 作为可从 Scrapy callable defined as a coroutine

您可以在定义为协程的scrapy可调用中等待的内容取决于 TWISTED_REACTOR

如果要编写使用 Deferred 对象,但适用于任何反应器,请在所有 Deferred 对象::

class MySpider(Spider):
    ...
    async def parse(self, response):
        d = treq.get('https://example.com/additional')
        extra_response = await maybe_deferred_to_future(d)

小技巧

如果您需要在旨在与不提供这些函数的较低版本的Scrapy兼容的代码中使用这些函数,请使用Scrapy 2.0(较早版本不支持 asyncio ),您可以将这些函数的实现复制到您自己的代码中。