0

我正在尝试执行一些基准测试并遇到一些请求问题。问题是,如果响应时间很长,则会引发一些错误。else如果request.get等待超过例如 2 秒,我怎样才能让它返回。

time = requests.get('http://www.google.com').elapsed.total_seconds()

if time < 1:
    print "Low response time"
else:
    print "High reponse time"
4

2 回答 2

1

使用超时参数requests.get。如果请求花费的时间超过超时值,requests.get将引发异常。requests.exceptions.Timeout

try:
    resp = requests.get('http://www.google.com', timeout=1.0)
except requests.exceptions.Timeout as e:
    print "High reponse time"
else:
    print "Low response time"
于 2016-03-10T13:53:30.967 回答
0

我不知道叫什么错误(你的意思是这里的例外吗?)。如果它抛出异常,那么你可以把它放在 try / except 中:

try:
    time = requests.get('http://www.google.com').elapsed.total_seconds()
    if time < 1:
        print "Low response time"
    else:
        print "High response time"
except:
    # threw an exception
    print "High response time"

如果您知道抛出的异常类型,那么我将设置 except 以捕获该异常而不捕获其他异常。

于 2016-03-10T13:40:55.937 回答