更新:https://requests.readthedocs.io/en/master/user/advanced/超时
在新版本的请求:
如果你为超时指定一个单独的值,像这样:
r = requests.get('https://github.com', timeout=5)
超时值将应用于连接超时和读取超时。如果你想分别设置值,请指定一个元组:
r = requests.get('https://github.com', timeout=(3.05, 27))
如果远程服务器非常慢,您可以告诉Requests永远等待响应,方法是将None作为超时值,然后检索一杯咖啡。
r = requests.get('https://github.com', timeout=None)
我以前的答案(可能已经过时了)(很久以前贴出来的):
还有其他方法可以克服这个问题:
1. 使用TimeoutSauce内部类
来自:https://github.com/kennethreitz/requests/issues/1928 # issuecomment - 35811896
import requests from requests.adapters import TimeoutSauce
class MyTimeout(TimeoutSauce):
def __init__(self, *args, **kwargs):
connect = kwargs.get('connect', 5)
read = kwargs.get('read', connect)
super(MyTimeout, self).__init__(connect=connect, read=read)
requests.adapters.TimeoutSauce = MyTimeout
This code should cause us to set the read timeout as equal to the
connect timeout, which is the timeout value you pass on your
Session.get() call. (Note that I haven't actually tested this code, so
it may need some quick debugging, I just wrote it straight into the
GitHub window.)
2. 使用kevinburke请求的分支:https://github.com/kevinburke/requests/tree/connect-timeout
从它的文档:https://github.com/kevinburke/requests/blob/connect-timeout/docs/user/advanced.rst
如果你为超时指定一个单独的值,像这样:
R = requests.get('https://github.com', timeout=5)
超时值将应用于连接和读取
超时。如果要设置值,请指定一个元组
另外:
R = requests.get('https://github.com', timeout=(3.05, 27))
Kevinburke已请求将其合并到主要请求项目中,但尚未被接受。