【问题标题】:The best solution for wait api response in pythonpython中等待api响应的最佳解决方案
【发布时间】:2020-12-26 00:11:44
【问题描述】:

我需要在一定时间内等待服务器成功响应。 最简单的方法:

def wait_for_response():
    response = None
    time = 60
    while time > 0:
        response = requests.get(url=some_url)
        if response:
            break
        time.sleep(5)
        time -= 5
    if not response:
        print("SOME ERROR")
    return response.json()

但我不认为这个解决方案是好的。还有其他更好的解决方案吗? 请注意,程序只有在函数完成工作后才能继续工作

【问题讨论】:

标签: python python-3.x asynchronous async-await python-requests


【解决方案1】:

requests.get() 是等待请求的函数...你能做的最好的就是给函数添加一个 timeout={seconds} 参数,例如:

requests.get(some_url, timeout=60)

它将等待 60 秒等待请求完成,然后抛出错误。

【讨论】:

  • 我不需要等待服务器本身的响应!我需要等到答案很好。例如,服务的答案可以是 404。但我需要等待一分钟,直到答案是 200
  • 糟糕.. 必须是and int(time.time()-t) < timeout
猜你喜欢
  • 2011-02-25
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 2011-11-18
  • 2012-03-31
  • 2020-04-12
  • 1970-01-01
  • 2023-03-13
相关资源
最近更新 更多