笨鸟编程-零基础入门Pyhton教程

 找回密码
 立即注册

协同程序

发布者: 笨鸟自学网



异步协同程序可用于调用。这包括其他协同程序、返回延迟的函数和返回的函数 awaitable objects 如 Future . 这意味着您可以使用许多有用的Python库来提供以下代码:

class MySpiderDeferred(Spider):
    # ...
    async def parse(self, response):
        additional_response = await treq.get('https://additional.url')
        additional_data = await treq.content(additional_response)
        # ... use response and additional_data to yield items and requests

class MySpiderAsyncio(Spider):
    # ...
    async def parse(self, response):
        async with aiohttp.ClientSession() as session:
            async with session.get('https://additional.url') as additional_response:
                additional_data = await additional_response.text()
        # ... use response and additional_data to yield items and requests

注解

例如许多类库 aio-libs ,需要 asyncio 循环并使用它们你需要 enable asyncio support in Scrapy .

注解

如果你想 await 在使用异步反应器时,您需要 wrap them 

异步代码的常见用例包括:

  • 从网站、数据库和其他服务(回调、管道和中间件)请求数据;

  • 在数据库中存储数据(在管道和中间件中);

  • 将spider初始化延迟到某个外部事件(在 spider_opened 经办人);

  • 调用诸如 ExecutionEngine.download (见 the screenshot pipeline example 

12
上一篇:作业:暂停和恢复爬行下一篇:asyncio

Archiver|手机版|笨鸟自学网 ( 粤ICP备20019910号 )

GMT+8, 2024-9-8 11:55 , Processed in 0.038159 second(s), 17 queries .

© 2001-2020

返回顶部