Handling an connection error with Twython
MRAB
python at mrabarnett.plus.com
Thu May 23 19:26:04 EDT 2019
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.
More information about the Python-list
mailing list