gpt4 book ai didi

python - 不可能捕获 asyncio.TimeoutError 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 20:33:13 35 4
gpt4 key购买 nike

我使用 asyncio 来获取 url,有时会超时,尽我所能,我无法使用以下代码捕获 asyncio.TimeoutError!

async def fetch(url, session):
"""Fetch a url, using specified ClientSession."""
async with session.get(url) as response:
# print(f"fetching {url}")
try:
resp = await response.read()
except asyncio.TimeoutError:
return {"results": f"timeout error on {url}"}

if response.status != 200:
return {"error": f"server returned {response.status}"}

return str(resp, 'utf-8').rstrip()

这是堆栈跟踪。我该怎么做才能捕获此异常并记录它而不是退出我的程序?

 resource: {…}  
severity: "ERROR"
textPayload: "Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 346, in run_http_function
result = _function_handler.invoke_user_function(flask.request)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function
return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 210, in call_user_function
return self._user_function(request_or_event)
File "/user_code/main.py", line 230, in gcf_update_all_featured_podcasts
loop.run_until_complete(future) # loop until done
File "/opt/python3.7/lib/python3.7/asyncio/base_events.py", line 573, in run_until_complete
return future.result()
File "/user_code/main.py", line 201, in fetch_all
_ = await asyncio.gather(*tasks) # gather task responses
File "/user_code/main.py", line 181, in fetch
async with session.get(url) as response:
File "/env/local/lib/python3.7/site-packages/aiohttp/client.py", line 1005, in __aenter__
self._resp = await self._coro
File "/env/local/lib/python3.7/site-packages/aiohttp/client.py", line 497, in _request
await resp.start(conn)
File "/env/local/lib/python3.7/site-packages/aiohttp/client_reqrep.py", line 857, in start
self._continue = None
File "/env/local/lib/python3.7/site-packages/aiohttp/helpers.py", line 585, in __exit__
raise asyncio.TimeoutError from None
concurrent.futures._base.TimeoutError

最佳答案

在回溯中,您可以看到异常是从您尝试向 url 发出请求的行引发的,但您的 try block 位于下面一层。

尝试这样:

async def fetch(url, session):
"""Fetch a url, using specified ClientSession."""
try:
async with session.get(url) as response:
# print(f"fetching {url}")
resp = await response.read()
if response.status != 200:
return {"error": f"server returned {response.status}"}

return str(resp, 'utf-8').rstrip()

except asyncio.TimeoutError:
return {"results": f"timeout error on {url}"}

关于python - 不可能捕获 asyncio.TimeoutError 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57349836/

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