Reputation: 61
I have that code
async with aiohttp.ClientSession() as session:
content = 'none'
while content == 'none':
try:
async with session.get(url) as resp:
resp.raise_for_status()
content = await resp.json()
except aiohttp.ClientError:
await asyncio.sleep(1)
except Exception as e:
print(e)
await asyncio.sleep(1)
I want make request while result is good, but if i compile this, sometimes result is 'none'. How make it better.
Upvotes: 5
Views: 2074
Reputation: 66341
I use async-retrying
for that. You mark the request function with the @retry
decorator and it will be re-run if an exception is raised. Example:
import asyncio
import aiohttp
from async_retrying import retry
@retry(attempts=100)
async def req(session, url):
async with session.get(url) as resp:
resp.raise_for_status()
return await resp.json()
async def main():
async with aiohttp.ClientSession() as session:
payload = await req(session, "http://eu.httpbin.org/get")
print("payload received:", payload)
if __name__ == "__main__":
asyncio.run(main())
Upvotes: 3