Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python requests.get gets stuck

I am making a python to read temperature from a simple server in a lan network each 2 seconds, the problem is that sometimes the script is stuck without doing anything, I'm using requests with python 3.6 on windows

import requests
import time

while True:
    s=time.time()

    r = requests.get("http://192.168.1.2/readtemp.php?id=1&action=read")
    temp = r.text
    print (temp + ' - ' + str(time.time()-s) + ' Seconds')
    time.sleep(2)

the response I get is this:

29°C - 0.272745847702026 Seconds

29°C - 0.64812617301941 Seconds

29°C - 0.294319868087769 Seconds

but sometimes when I come back to my computer I find it stuck doing nothing, any ideas why it gets stuck, isn't it supposed to keep making the request till it gets a response like browsers do?

like image 941
M. Serseg Avatar asked Apr 08 '18 19:04

M. Serseg


1 Answers

As Tobias wrote, requests doesn't retry nor have a timeout by default, as using a timeout would inform you about a potential (and the most likely, my opinion) issue. Either catch the exception and retry later or you can go the more advanced route of a retry adapter.

Try this request with timeout & error handling:

import requests
import time

while True:
    s=time.time()

    try: 
        r = requests.get("http://192.168.1.2/readtemp.php?id=1&action=read", timeout=10)
    except requests.exceptions.Timeout as err: 
        print(err)
        # sleep some sec/min and retry here!

    temp = r.text
    print (temp + ' - ' + str(time.time()-s) + ' Seconds')

    time.sleep(2)
like image 119
DaWe Avatar answered Sep 28 '22 01:09

DaWe