【问题标题】:setting the timeout on a urllib2.request() call在 urllib2.request() 调用上设置超时
【发布时间】:2013-05-20 09:22:06
【问题描述】:

我需要在urllib2.request() 上设置超时。

我不使用urllib2.urlopen(),因为我使用的是requestdata 参数。我该如何设置?

【问题讨论】:

  • 全局设置超时时间,可以使用socket.setdefaulttimeout()

标签: python urllib2


【解决方案1】:

虽然urlopen 接受POSTdata 参数,但您可以像这样在Request 对象上调用urlopen

import urllib2
request = urllib2.Request('http://www.example.com', data)
response = urllib2.urlopen(request, timeout=4)
content = response.read()

【讨论】:

  • @MöbiusStripMall 秒 (manual)
  • 请注意,timeout 确实支持浮点值。将其设置为 0.1 按预期工作。在任何地方都找不到此文档。
【解决方案2】:

不过,你可以避免使用 urlopen 并像这样继续:

request = urllib2.Request('http://example.com')
response = opener.open(request,timeout=4)
response_result = response.read()

这也有效:)

【讨论】:

  • 不使用urlopen有什么好处?
  • @jsc123: opener 大概是使用 build_opener() 创建的,它允许您为多个请求配置参数,例如,这里是 an opener that allows to make http requests via a tor socks5 proxy。此外,如果您使用多个线程,您可能需要创建一个显式 openerurlopen() 使用全局数据)。
【解决方案3】:

为什么不使用很棒的requests?你会为自己节省很多时间。

如果您担心部署,只需将其复制到您的项目中即可。

例如。请求数:

>>> requests.post('http://github.com', data={your data here}, timeout=10)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-04
    • 2012-12-18
    • 1970-01-01
    • 2017-01-01
    • 2012-03-15
    • 1970-01-01
    • 2010-09-28
    • 2014-08-27
    相关资源
    最近更新 更多