如何发送异步超时请求



我需要向某个服务器发出请求。如果服务器在500毫秒内没有响应,我需要再发送两个(完全相同的(请求,并返回三个已经完成的请求中的第一个。我尝试过eventlet、grequests,有点害怕制作和管理自己的线程。我迷失在多种可能的变体之间。以下是部分代码,但不确定这是否有帮助:

api_responses = []
api_responses.append(grequests.get(URL))
with stopit.ThreadingTimeout(0.5) as first_req_mgr:
grequests.map(api_responses)
while True:
if api_responses[0].status_code == 200:
break
if first_req_mgr.state == first_req_mgr.TIMED_OUT:
#send two more requests and wait in while true loop for any of them to return successful response

编辑:第一个请求不应该在500秒后被杀死

如果线程不是必须的,请尝试以下逻辑:

api_responses = []
for i in range(3):
if api_responses:
break
if grequests.get(URL).status_code == 200:    
api_responses.append(grequests.get(URL))

最新更新