Requests: 功能请求:为会话添加超时

创建于 2014-04-21  ·  11评论  ·  资料来源: psf/requests

似乎进入发送的每个可选参数也可以在会话中设置(例如验证、流等)。 除了超时。

是否可以更改行为,以便像所有其他参数一样从会话中合并超时?

最有用的评论

为什么不只是填充request方法?

s = requests.Session()
s.request = functools.partial(s.request, timeout=3)
# this should now timeout
s.get('https://httpbin.org/delay/6')

所有11条评论

@ctheiss嘿,感谢您提出这个问题!

这是以前出现过的,最近一次出现在 #1987 中,但也出现在 #1130 和 #1563(今年都是)。 Kenneth 普遍表示对进行此更改缺乏兴趣,希望使用传输适配器来完成。 如果您有兴趣获得有关如何执行此操作的指导,我很乐意提供帮助,但我认为我们不会将timeoutSession .

对不起,我们不能提供更多帮助!

感谢您的超快速响应。 我需要更好地搜索问题,因为您提到的问题完全重复!

是实现BaseAdapter (或子类HTTPAdapter ),然后使用mount将子类与会话相关联的想法吗? 仅仅实现“默认超时”似乎很费力(考虑到请求中的其他所有内容都非常简单)。

这个想法是将HTTPAdapter子类化。 这不是很费力,真的,但我们这样做的主要原因是因为它在库中保持了概念上的区别。 Session对象应该严格管理有关 HTTP 本身如何工作的会话的事情:cookie、标头等。 传输适配器管理有关网络连接如何工作的事情:套接字、超时等。

澄清一下,您的建议是人们这样做?

class MyHTTPAdapter(requests.adapters.HTTPAdapter):
    def __init__(self, timeout=None, *args, **kwargs):
        self.timeout = timeout
        super(MyHTTPAdapter, self).__init__(*args, **kwargs)

    def send(self, *args, **kwargs):
        kwargs['timeout'] = self.timeout
        return super(MyHTTPAdapter, self).send(*args, **kwargs)

s = requests.Session()
s.mount("http://", MyHTTPAdapter(timeout=10))

@staticshock这是一个选项。 是的

但是,更具体地说,是_推荐_吗?

没有具体的建议,因为用户的需求会有所不同,并且有多种方法可以为这些用户解决这个问题。

@staticshock @sigmavirus24

该解决方案似乎过于复杂。 以下似乎对我有用。

s = requests.Session()
s.get_orig, s.get = s.get, functools.partial(s.get, timeout=3)
# this should now timeout
s.get('https://httpbin.org/delay/6')
# and this should succeed
s.get_orig('https://httpbin.org/delay/6')

@staticshock @sigmavirus24

该解决方案似乎过于复杂。 以下似乎对我有用。

s = requests.Session()
s.get_orig, s.get = s.get, functools.partial(s.get, timeout=3)
# this should now timeout
s.get('https://httpbin.org/delay/6')
# and this should succeed
s.get_orig('https://httpbin.org/delay/6')

请注意,如果您使用这些动词,您还需要将此应用于其他动词,例如postput等。 为了完整起见,这是我正在使用的:

session = requests.Session()
for method in ('get', 'options', 'head', 'post', 'put', 'patch', 'delete'):
    setattr(session, method, functools.partial(getattr(session, method), timeout=5))
# All methods of session should now timeout after 5 seconds

为什么不只是填充request方法?

s = requests.Session()
s.request = functools.partial(s.request, timeout=3)
# this should now timeout
s.get('https://httpbin.org/delay/6')

如果您在模块级别全局需要它并且不使用会话,您可能会这样做:

requests.api.request = functools.partial(requests.api.request, timeout=3)

我不确定这如何在多个模块中使用它,我想您在使用请求的每个文件中都需要垫片。

此页面是否有帮助?
0 / 5 - 0 等级