简体   繁体   中英

Handling Python HTTP connection timeout

I am trying to read a status from four web servers that monitor fluid tanks with an HTTP connection. It is not unusual for one or more of these servers to not be present, but that's okay, I just want to record a timeout error and continue to the other servers and get their status. I cannot figure out how to handle the timeout when it occurs? And always open to any other critique on this code... I'm brand new to Python.

# Fluid tank Reader
import http.client

activeTanks = 4;
myTanks=[100,100,100,100]

for tank in range(0,activeTanks):
    tankAddress = ("192.168.1.4"+str(tank))
    conn = http.client.HTTPConnection(tankAddress, timeout=1)
    ##  How do I handle the exception and finish the For Loop?
    conn.request("GET", "/Switch=Read")
    r1 = conn.getresponse()
    conn.close()
    myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1])

print(myTanks)  # this will pass data back to a main loop later

You should add handler for socket.timeout exception:

import http.client
import socket


activeTanks = 4  # no semicolon here
myTanks = [100, 100, 100, 100]

for tank in range(0, activeTanks):
    tankAddress = ("192.168.1.4" + str(tank))
    conn = http.client.HTTPConnection(tankAddress, timeout=1)

    try:
        conn.request("GET", "/Switch=Read")
    except socket.timeout as st:
        # do some stuff, log error, etc.
        print('timeout received')
    except http.client.HTTPException as e:
        # other kind of error occured during request
        print('request error')
    else:  # no error occurred
        r1 = conn.getresponse()
        # do some stuff with response
        myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1])
    finally:  # always close the connection
        conn.close()

print(myTanks)

As in other languages, you catch the exception and treat it: (NB: I placed it there, but it's up to you)

** Fluid tank Reader
import http.client

activeTanks = 4;
myTanks=[100,100,100,100]

for tank in range(0,activeTanks):
    tankAddress = ("192.168.1.4"+str(tank))
    conn = http.client.HTTPConnection(tankAddress, timeout=1)
    ##  How do I handle the exception and finish the For Loop?
    try:
        conn.request("GET", "/Switch=Read")
        r1 = conn.getresponse()
        myTanks[tank] = int(r1.read().decode('ASCII').split("...")[1])
    except http.client.HTTPException:
        do something
    finally:
        conn.close() #ensures you cleanly close your connection each time, thanks @schmee


print(myTanks)  **  this will pass data back to a main loop later

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM