Python urllib2设置超时

时间:2015-12-05 16:40:33

标签: python post timeout urllib2

我尝试使用Python的urllib2模块发出POST请求来获取网址。我按以下方式构建请求。

handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
url = 'xyz...'
request = urllib2.Request(url,data='{}')
request.add_header('Content-Type','application/json')
request.get_method = lambda: 'POST'
try:
   connection = opener.open(request)
except urllib2.HTTPError as e:
   connection = e
except urllib2.URLError as e:
   print 'TIMEOUT: ' + e.reason

我想在某处设置打开请求的超时。根据文档https://docs.python.org/3.1/library/urllib.request.html build_opener()调用应该返回一个应该有超时参数的OpenDirector实例。但我似乎无法让它发挥作用。另外,我构建请求的原因是因为我需要在请求中指定一个空主体data='{}',而我似乎无法通过urlopen来实现这一点无论是。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

您可以将timeout作为参数传递给开场白的open方法调用。

使用lambda函数正常运行以确保请求为POST,而不是GET没有正文

>>> import urllib2
>>> handler = urllib2.HTTPHandler()
>>> opener = urllib2.build_opener(handler)
>>> request = urllib2.Request('http://httpbin.org/post')
>>> request.get_method = lambda: 'POST'
>>> opener.open(request)
<addinfourl at 4363264800 whose fp = <socket._fileobject object at 0x101b654d0>>

只需添加timeout

即可
>>> opener.open(request, timeout=0.01)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 431, in open
    response = self._open(req, data)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 449, in _open
    '_open', req)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1227, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1197, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error timed out>