Ok so I have two questions about the same code:
Question 1)
Say that I make a request. When that request goes past .5 second, I want it to end the current iteration and retry the connection. Basically, if it fails to get a request, I want it to either try again or exit the iteration so that it can try again. How do I do this? So with the code below, after a while, it gives me a "read time out" error. How do I fix this?
import requests
import json
import time
import sys
def calcProfits():
url = 'https://api.gdax.com/products/BTC-USD/trades'
t0 = time.time() #timer i made to see if the "timeout" works
res = requests.get(url, timeout = .5) #i want it to retry after 1 second of failing to get a response, is this correct?
t1 = time.time()
total_time = round((t1-t0),3)
json_res = json.loads(res.text)
currDollarBit = float(json_res[0]['price'])
sys.stdout.write(str(currDollarBit) + " ")
sys.stdout.write(str(total_time) + "\n")
time.sleep(1)
while True:
calcProfits()
Question 2)
So I came across this question and tried to use except. but I still see that the request is passing the 0.5 seconds i set up in the timeout and nothing is happening. eventually, it does a timeout and it says "UnboundLocalError: local variable 'res' referenced before assignment". i guessing that if it timeout, the res variable is completely ignored? Heres the code:
import requests
import json
import time
import sys
def calcProfits():
url = 'https://api.gdax.com/products/BTC-USD/trades'
try:
t0 = time.time() #timer i made to see if the "timeout" works
res = requests.get(url, timeout = .5)
t1 = time.time()
total_time = round((t1-t0),3)
except Exception as e:
print("\nTIMEOUT\n")
json_res = json.loads(res.text)
currDollarBit = float(json_res[0]['price'])
sys.stdout.write(str(currDollarBit) + " ")
sys.stdout.write(str(total_time) + "\n")
time.sleep(1)
while True:
calcProfits()
Anyways how do i fix it so that it just retires after that 0.5 seconds?