我正在尝试执行一些基准测试,但请求遇到了一些问题。问题是,如果响应时间很高,则会抛出一些错误。如果request.get
等待超过 2 秒,我如何让它返回else
。
time = requests.get('http://www.google.com').elapsed.total_seconds()
if time < 1:
print "Low response time"
else:
print "High reponse time"
使用 requests.get
的超时参数。 如果请求花费的时间超过超时值requests.exceptions.Timeout
requests.get
将引发异常。
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"
我不知道什么
错误叫(你的意思是这里的例外吗?如果它抛出异常,那么您可以将其放入尝试/除了:
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"
如果您知道抛出的异常类型,那么我会设置除了捕获该异常而没有其他异常。