jy2da
jy2da

Reputation: 45

Building a retry mechanism in a while loop in python

while true:
    ticker = binance.fetch_ticker("BTC/USDT")
    current_price = ticker['last']
function_A(current_price)

I have a while loop that keeps running to check the current price of Bitcoin every second. Then I also have a function that takes current_price as an input.

However, occasionally, I am getting

"requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))"

So I'm trying to use try, except to make a retry mechanism whenever this error comes up. I've tried this:

while true:
    try_count = 10
    while try_count > 0:
        try:
            ticker = binance.fetch_ticker("BTC/USDT")
            current_price = ticker['last']
            try_count = 0
            break
        except (requests.ConnectionError, requests.ReadTimeout) as error:
            print(error, " detected. Trying again...")
            try_count -= 1
    function_A(current_price)

The problem is that if I do this, current_price ends up being undefined when I plug it in as an input in function_A on the last line. How can I fix this mechanism?

Upvotes: 2

Views: 1216

Answers (2)

Capybara
Capybara

Reputation: 782

Defining current_price in a scope outside the second while loop can prevent the problem with current_price sometimes being undefined when calling function_A.

while True:
    current_price = None
    try_count = 10
    while try_count > 0:
        try:
            ticker = binance.fetch_ticker("BTC/USDT")
            current_price = ticker['last']
            try_count = 0
            break
        except (requests.ConnectionError, requests.ReadTimeout) as error:
            print(error, " detected. Trying again...")
            try_count -= 1
    if current_price is not None:
        function_A(current_price) 

Upvotes: 1

mkjh
mkjh

Reputation: 1654

you may want to explore the backoff library which helps to retry your function. https://pypi.org/project/backoff/

you can just add a backoff decorator on fetch_ticker function and it should retries when it hits RequestException error.

the code should look something like

@backoff.on_exception(backoff.expo, requests.exceptions.RequestException)
def fetch_ticker(ticker):
    # binance.fetch_ticker

Upvotes: 0

Related Questions