Python请求的超时值是否指向收到的第一个字节或整个消息?

时间:2017-04-06 10:34:29

标签: python

文档(http://docs.python-requests.org/en/latest/api/#requests.request)解释了timeout这样的值:

  

timeout(float或tuple) - (可选)等待服务器的时间   在放弃之前发送数据,作为浮点数,或者(连接超时,读取   超时)元组。

response = requests.post(url, data=post_fields, timeout=timeout)

这是否意味着等待服务器发送单个字节,或者等待服务器发送"整个"信息?换句话说,是一个timeout值(不是元组),read()调用的超时?

1 个答案:

答案 0 :(得分:2)

如果将timeout指定为float(不是元组),那么这相当于指定一个元组具有相同值的元组:

import requests

try:
    response = requests.post('http://httpbin.org/post', timeout=0.1)
except requests.exceptions.Timeout as e:
    print(e)

如果将timeout设置得非常小(0.001),那么我们会得到ConnectTimeoutError

HTTPConnectionPool(host='httpbin.org', port=80): Max retries exceeded with url: /post (Caused by ConnectTimeoutError(<requests.packages.urllib3.connection.HTTPConnection object at 0x039970D0>, 'Connection to httpbin.org timed out. (connect timeout=0.001)'))

稍微增加此值(0.1)会导致连接建立成功,但read()次超时:

HTTPConnectionPool(host='httpbin.org', port=80): Read timed out. (read timeout=0.1)