【发布时间】:2013-05-20 09:22:06
【问题描述】:
我需要在urllib2.request() 上设置超时。
我不使用urllib2.urlopen(),因为我使用的是request 的data 参数。我该如何设置?
【问题讨论】:
-
全局设置超时时间,可以使用
socket.setdefaulttimeout()
我需要在urllib2.request() 上设置超时。
我不使用urllib2.urlopen(),因为我使用的是request 的data 参数。我该如何设置?
【问题讨论】:
socket.setdefaulttimeout()
虽然urlopen 接受POST 的data 参数,但您可以像这样在Request 对象上调用urlopen,
import urllib2
request = urllib2.Request('http://www.example.com', data)
response = urllib2.urlopen(request, timeout=4)
content = response.read()
【讨论】:
timeout 确实支持浮点值。将其设置为 0.1 按预期工作。在任何地方都找不到此文档。
不过,你可以避免使用 urlopen 并像这样继续:
request = urllib2.Request('http://example.com')
response = opener.open(request,timeout=4)
response_result = response.read()
这也有效:)
【讨论】:
opener 大概是使用 build_opener() 创建的,它允许您为多个请求配置参数,例如,这里是 an opener that allows to make http requests via a tor socks5 proxy。此外,如果您使用多个线程,您可能需要创建一个显式 opener(urlopen() 使用全局数据)。
为什么不使用很棒的requests?你会为自己节省很多时间。
如果您担心部署,只需将其复制到您的项目中即可。
例如。请求数:
>>> requests.post('http://github.com', data={your data here}, timeout=10)
【讨论】: