尝试获取从异步 aiohttp get 调用返回的 2 个值

Trying to get 2 values returned from async aiohttp get call

今天我试图加速我的脚本,并从另一个 Whosebug post 中找到了很好的示例代码。基本上,我找到了一种使用 aiohttp 向网络发出异步请求而不是使用请求的方法。这是 post 的 link (我从 DragonBobZ 的回答中复制了代码)。

Link to other Whosebug post from which I copied code

问题是我试图让它达到 return 2 个值(url,响应),而不仅仅是请求的响应。这是我拿的代码。

def async_aiohttp_get_all(urls, cookies):
    async def get_all(urls):
        async with aiohttp.ClientSession(cookies=cookies) as session:
            async def fetch(url):
                async with session.get(url) as response:
                    return await response.json()
            return await asyncio.gather(*[
                fetch(url) for url in urls
            ])

    return sync.async_to_sync(get_all)(urls)

for x in async_aiohttp_get_all(urls_list, s.cookies.get_dict()):
    print(x)

现在我能够在请求所花费的时间的一小部分内成功地获得所有 url 的响应,但我希望该函数也 return url 具有:

return await response.json()

我试过了,但没有任何效果,这是我第一天在 python 中使用异步实践,所以我什至无法搜索解决方案,因为没有任何意义。

return await url, response.json()
return await (url, response.json())

我无法 运行 代码完全按照您的方式执行,但我返回了一个元组没有问题。还删除了 sync 调用,因为 asyncio 为您提供了足够的灵活性。

import asyncio
import aiohttp

urls_list = [
    "https://www.google.com",
    "https://www.facebook.com",
    "https://www.twitter.com",
]

async def async_aiohttp_get_all(urls, cookies):
    async with aiohttp.ClientSession(cookies=cookies) as session:
        async def fetch(url):
            async with session.get(url) as response:
                return await response.text(), url
        return await asyncio.gather(*[
            fetch(url) for url in urls
        ])

results = asyncio.run(async_aiohttp_get_all(urls_list, None))
for res in results:
    print(res[0][:10], res[1])

输出:

<!doctype  https://www.google.com
<!DOCTYPE  https://www.facebook.com
<!DOCTYPE  https://www.twitter.com

因此,对于您的情况,return await response.json(), url 应该有效。