aiohttp 异步网络请求范式
最近看爬虫项目看到有人代码这样写
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
一般会将 session 作为参数传入, 写法2:
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async with aiohttp.ClientSession() as session:
fetch(session, url)
以前就是觉得挺怪的,也没想过为什么。现在有gpt了直接问
是为了减少创建ClientSession的开销,而且写法2是在官方文档强烈推荐并进行说明的