Get request in Python terminates the program when there is no connection

Asked

Viewed 282 times

1

I am developing a Python application to check the external IP and save in a database, the problem is the following function:

def pega_ip(): ip = get('https://api.ipify.org').text return ip

Because she uses the method get to receive the content directly in a variable, when there is no internet connection, the error occurs:

file "/usr/local/lib/python3.5/dist-Packages/requests/Adapters.py", line 508, in send raise Connectionerror(e, request=request) requests.exceptions.Connectionerror: httpsconnectionpool(host='api.ipify.org', port=443): Max retries exceeded with url: / (Caused by Newconnectionerror(': Failed to Establish a new Connection: [Errno -3] Temporary Failure in name Resolution',))

I need to treat this problem because the program is finished when this error occurs, I need that if the connection falls it continues running and trying to access this url to get the external IP.

1 answer

1


You just have to put in one while and take the exception when it occurs:

def pega_ip(): 
    while True:
        try:
            ip = get('https://api.ipify.org').text
            return ip
        except ConnectionError:
            pass

So, if there is an exception, he will immediately try again. If there is not, he arrives at the return and the function is terminated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.