gpt4 book ai didi

python aiohttp超时是针对单个TCP连接还是针对http请求?

转载 作者:行者123 更新时间:2023-12-02 02:38:36 24 4
gpt4 key购买 nike

在 python aiohttp 中,我们可以在 ClientSession 或(例如)session.get 中设置超时。 https://docs.aiohttp.org/en/stable/client_quickstart.html

假设我们这样做

async with aiohttp.ClientSession(timeout=<customized timeout>) as session: 
async with session.get(<url1>):
xxx
async with session.get(<url2>):
xxx

自定义超时是针对整个与aiohttp.ClientSession()的异步还是针对每个与session.get的异步

最佳答案

超时针对每个单独的请求;你可以像这样测试它:

import asyncio
import aiohttp
import random

async def main():
timeout = aiohttp.ClientTimeout(total=3)
async with aiohttp.ClientSession(timeout=timeout) as session:
base_url = "http://httpbin.org/delay/%d"
for i in range(10):
url = base_url % random.randint(1, 5)
try:
async with session.get(url) as response:
data = await response.json()
print(f"step {i}, url {url}, status {response.status}, keys: {len(data)}")
except asyncio.exceptions.TimeoutError:
print(f"step {i}, url {url}, status timeout")

asyncio.run(main())

我的计算机上的结果:

step 0, url http://httpbin.org/delay/5, status timeout
step 1, url http://httpbin.org/delay/5, status timeout
step 2, url http://httpbin.org/delay/2, status 200, keys: 7
step 3, url http://httpbin.org/delay/4, status timeout
step 4, url http://httpbin.org/delay/4, status timeout
step 5, url http://httpbin.org/delay/3, status 200, keys: 7
step 6, url http://httpbin.org/delay/2, status 200, keys: 7
step 7, url http://httpbin.org/delay/3, status 200, keys: 7
step 8, url http://httpbin.org/delay/1, status 200, keys: 7
step 9, url http://httpbin.org/delay/2, status 200, keys: 7

关于python aiohttp超时是针对单个TCP连接还是针对http请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63959515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com