inyutin/aiohttp_retry

Fallback Functionality

a2z72 opened this issue · 4 comments

a2z72 commented

Hello,

Thanks for this wonderful library.

I'm wondering how to customize the behavior when all tries are exhausted to return None, even if the last request ended in an exception?

I understand the following from the documentation: "last request returns as it is.
If the last request ended with exception, that this exception will be raised from RetryClient request" - but I'd like to continue despite the exception raised by returning None.

Hello, @a2z72 !

I'm afraid I don't quite understand your needs. Can you, please, describe everything more briefly ?
If I understand correctly, you want to receive None as a response, if the last request failed. Can you describe why do you need such functionality ?

Why not to do something like that then?

try:
    response = await aiohttp_client.request(...)
except:
    response = None

You can also set up a huge number of attempts, so there will be requests until success

a2z72 commented

Hi @inyutin - thanks for your prompt reply.

Here's the code I'm trying to model the functionality of:

    while attempts <= max_tries:
        try:
            async with request("GET", url) as response:
                return await response.text("utf-8")
        except:
            attempts += 1
            continue
    return None # fallback

I would like to try the HTTP request X number of times, and if on the last request an exception is still thrown, the function will return None (instead of raising an exception).

@a2z72 then code like that should fulfills your needs:

from aiohttp import ClientResponse
from aiohttp_retry import RetryClient, RandomRetry

async def make_requests(url: str, max_tries: int) -> Optional[ClientResponse]:
    retry_options = ExponentialRetry(attempts=max_tries)
    async with RetryClient(retry_options=retry_options, raise_for_status=True) as client:
          try:
              async with client.get(url) as response:
                  return response 
          except:
              # logger.warning/logger.exception
              return None   

I don't feel, that adding an option to return None instead of raw response in case of failure is a correct thing.
As I stated above it's pretty easy to achieve the behaviour you want. Maybe I don't get your request in a right way? Do you have any more questions?

a2z72 commented

Thank you @inyutin.