Handling an connection error with Twython

Cecil Westerhof Cecil at decebal.nl
Fri May 24 01:49:23 EDT 2019


MRAB <python at mrabarnett.plus.com> writes:

> On 2019-05-23 22:55, Cecil Westerhof wrote:
>> Cecil Westerhof <Cecil at decebal.nl> writes:
>>
>>> I am using Twython to post updates on Twitter. Lately there is now and
>>> then a problem with my internet connection. I am using:
>>>     posted = twitter.update_status(status = message,
>>>                                    in_reply_to_status_id = message_id,
>>>                                    trim_user = True)
>>>
>>> What would be the best way to catch a connection error and try it (for
>>> example) again maximum three times with a delay of one minute?
>>
>> At the moment I solved it with the following:
>>      max_tries   = 3
>>      current_try = 1
>>      while True:
>>          try:
>>              posted = twitter.update_status(status = message,
>>                                             in_reply_to_status_id = message_id,
>>                                             trim_user = True)
>>              return posted['id']
>>          except TwythonError as e:
>>              print('Failed on try: {0}'.format(current_try))
>>              if not 'Temporary failure in name resolution' in e.msg:
>>                  raise
>>              if current_try == max_tries:
>>                  raise
>>              current_try += 1
>>              time.sleep(60)
>>
>> Is this a good way to do it, or can it be improved on?
>>
>> When it goes OK I just return from the function.
>> If it goes wrong for something else as failure in the name resolution
>> I re-raise the exception.
>> When the maximum tries are done I re-raise the exception.
>> Otherwise I wait a minute to try it again.
>>
> You have a 'while' loop with a counter; you can replace that with a
> 'for' loop.

I did not do that consciously, because I have to try until it is
successful an I return, or I reached the max tries and re-raise the
exception. With a for loop I could exit the loop and cannot re-raise
the exception.

-- 
Cecil Westerhof
Senior Software Engineer
LinkedIn: http://www.linkedin.com/in/cecilwesterhof



More information about the Python-list mailing list