每天进步一点点:Requests的超时(timeout)设置

in #cn4 years ago

在好久好久之前,曾经写过几篇关于Requests的文章,但是对于超时(timeout)却没有提及,最近看几个朋友讨论Requests的超时问题,所以特意学习了一下。


(图源 :pixabay)

简单测试

为什么要讨论超时的问题呢?因为Requests链接或者访问数据时,并没有默认的超时设置,这就意味着,如果服务器端故障,导致无法连接等问题,那么Request就可能等待一分钟乃至更长的时间(甚至无限期地等待)。

我们可以通过如下代码进行简单测试:

requests.get('https://github.com:8888')

上边的代码等同于如下代码:

r = requests.get('https://github.com:8888', timeout=None)

实际测试,在等待几分钟之后方返回(时间应该取决于服务器的设置):

Failed to establish a new connection: [Errno 110] Connection timed out',))

而如果指定了timeout参数,那么当五秒钟过去,且并没有建立连接或者返回数据,那么就会返回Timeout错误:

requests.get('https://github.com:8888', timeout=5)

比如上述代码会返回类似如下内容:

'Connection to github.com timed out. (connect timeout=5)'))

由此可见,设置timeout参数是多么重要。难怪Requests文档中提示:Nearly all production code should use this parameter in nearly all requests.

高级设置

朋友在微信群中转发过来的一篇文章中提及:

requests请求上设置的timeout判断的并不是整个请求的总时间,而是从与服务器连接成功后,客户端开始接受服务器的数据为计算起点的。

为此我特意找了一下Requests的文档,其中关于timeout参数的说明中说到:

The timeout value will be applied to both the connect and the read timeouts

也就是说,朋友转发来的内容要么是错误的,要么是过时的。(所以看资料还是应该去官网)

除了用一个timeout指定超时参数外,也可以分别指定连接以及读取数据的超时时间,指定方法如下:

r = requests.get('https://github.com', timeout=(3.05, 27))

关于连接超时时间,从经验上看,一般设置为比3略大的数字,详细原因如下:

It’s a good practice to set connect timeouts to slightly larger than a multiple of 3, which is the default TCP packet retransmission window.

没想到小小的timeout参数还有这么多说道啊,看来以前了解的果然肤浅。

参考链接


Vote For Me As Witness
https://steemit.com/~witnesses type in oflyhigh and click VOTE

Vote @oflyhigh via Steemconnect
Thank you!

Coin Marketplace

STEEM 0.31
TRX 0.11
JST 0.034
BTC 64060.81
ETH 3129.62
USDT 1.00
SBD 4.17