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

1

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

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

Because it uses the get method to receive content directly into 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 handle this problem because the program is terminated when this error occurs, I need that if the connection crashes it will continue executing and trying to access this url in order to get the external IP.

    
asked by anonymous 31.01.2018 / 15:05

1 answer

1

You only have to put in while and catch 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, it will immediately try again. If it does not, it arrives at return and the function exits.

    
31.01.2018 / 16:37