HTTP请求超时 [英] HTTP Request Timeout

查看:402
本文介绍了HTTP请求超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 2.6中,httplib.HTTPConnection类添加了一个新的timeout参数:
http://docs.python.org/library/httplib.html#httplib.HTTPConnection

In Python 2.6, a new "timeout" parameter was added to the httplib.HTTPConnection class: http://docs.python.org/library/httplib.html#httplib.HTTPConnection

但是,这是只有连接到服务器的超时。我期待为请求设置超时值,而不是连接。这似乎不受httplib支持。

However, this is only a timeout for the connection to a server. I am looking to set a timeout value for the request, not the connection. This doesn't seem to be supported by httplib.

有没有办法模仿这种行为?

Is there any way to emulate this behavior?

推荐答案

您可以设置全局套接字超时(*)

You can set a global socket timeout (*):

import socket

timeout = 10
socket.setdefaulttimeout(timeout)






(*) 编辑:正如评论中的人正确指出:这在技术上是正确的,但它仅对涉及单个套接字操作的任务具有可预测的结果。 HTTP请求由多个套接字操作组成(例如,DNS请求或可能从HTTP客户端抽象出来的其他事物)。由于这个原因,整个操作的超时变得不可预测。


(*) EDIT: As people in the comments correctly point out: This is technically true, but it only has predictable results for tasks that involve a single socket operation. An HTTP request consists of multiple socket operations (e.g. DNS requests or other things that might be abstracted away from an HTTP client). The timeout of the overall operation becomes unpredictable because of that.

这篇关于HTTP请求超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆