【发布时间】:2019-08-04 20:02:03
【问题描述】:
我正在使用 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
【问题讨论】:
标签: python exception python-asyncio