W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
2.0 新版功能.
刮痧 partial support 對(duì)于 coroutine syntax .
以下可調(diào)用項(xiàng)可以定義為使用 ?async def
? ,因此使用協(xié)同程序語法(例如。 ?await
? , ?async for
? , ?async with
? ):
Request
? 回調(diào)。注解在整個(gè)回調(diào)完成之前,不會(huì)處理回調(diào)輸出。作為副作用,如果回調(diào)引發(fā)異常,則不會(huì)處理其任何輸出。這是對(duì)當(dāng)前實(shí)現(xiàn)的一個(gè)已知警告,我們將在Scrapy的未來版本中解決這個(gè)問題。process_item()
? 方法 item pipelines .process_request()
? , ?process_response()
? 和 ?process_exception()
? 方法 downloader middlewares .Scrapy中有幾個(gè)協(xié)同程序的用例。在為以前的垃圾版本(如下載程序中間件和信號(hào)處理程序)編寫時(shí),會(huì)返回延遲的代碼可以重寫為更簡短、更干凈:
from itemadapter import ItemAdapter
class DbPipeline:
def _update_item(self, data, item):
adapter = ItemAdapter(item)
adapter['field'] = data
return item
def process_item(self, item, spider):
adapter = ItemAdapter(item)
dfd = db.get_some_data(adapter['id'])
dfd.addCallback(self._update_item, item)
return dfd
變成::
from itemadapter import ItemAdapter
class DbPipeline:
async def process_item(self, item, spider):
adapter = ItemAdapter(item)
adapter['field'] = await db.get_some_data(adapter['id'])
return item
異步協(xié)同程序可用于調(diào)用。這包括其他協(xié)同程序、返回延遲的函數(shù)和返回的函數(shù) awaitable objects 如 ?Future
? . 這意味著您可以使用許多有用的Python庫來提供以下代碼:
class MySpider(Spider):
# ...
async def parse_with_deferred(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
async def parse_with_asyncio(self, response):
async with aiohttp.ClientSession() as session:
async with session.get('https://additional.url') as additional_response:
additional_data = await r.text()
# ... use response and additional_data to yield items and requests
注解
例如許多類庫 aio-libs ,需要 asyncio 循環(huán)并使用它們你需要 enable asyncio support in Scrapy .
異步代碼的常見用例包括:
spider_opened
? 經(jīng)辦人);Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: