【问题标题】:Use of urllib2 in Google App Engine throws "Deadline exceeded while waiting for HTTP response from URL:..."在 Google App Engine 中使用 urllib2 会引发“等待来自 URL 的 HTTP 响应时超出期限:...”
【发布时间】:2014-09-23 07:43:17
【问题描述】:

我在 python 中将 urllib2 用于 Google App Engine (GAE)。 应用程序经常因为以下错误而崩溃:

等待来自 URL 的 HTTP 响应时超过了最后期限:....

源代码如下所示:

import webapp2
import urllib2
from bs4 import BeautifulSoup

def functionRunning2To5Seconds_1()    
    #Check if the Url could be parsed
    try:
        url         ="http://...someUrl..."
        req         = urllib2.Request(url,headers={'User-Agent': 'Mozilla/5.0'})
        page        = urllib2.urlopen(req)
        htmlSource  = BeautifulSoup(page)
    except Exception  e:
        logging.info("Error : {er}".format(er=str(e)))

    #do some calculation with the data of htmlSource, which takes 2 To 5 Seconds

#and the handler looks like:
class xyHandler(webapp2.RequestHandler):
    def post(self, uurl=None):
        r_data1 = functionRunning2To5Seconds_1()
        r_data2 = functionRunning2To5Seconds_2()
        r_data3 = functionRunning2To5Seconds_3()
        ...
        #show the results in a web page

我发现了这个doc,它声明:

您可以使用 Python 标准库 urllib、urllib2 或 httplib 发出 HTTP 请求。在 App Engine 中运行时,这些库 使用 App Engine 的 URL 获取服务执行 HTTP 请求

还有这个:

您可以为请求设置截止日期,即最长时间 服务将等待响应。默认情况下,获取的截止日期 是 5 秒。 HTTP 请求的最大截止时间为 60 秒,并且 任务队列和 cron 作业请求为 60 秒。

那么我该怎么做呢?如何在 urllib2 上设置超时时间?

或者,我是否必须重写整个应用程序才能使用 App Engine 的 URL 获取服务?

(PS:有人知道并行运行“r_data1 = functionRunning2To5Seconds_...()”调用的安全方法吗?)

【问题讨论】:

    标签: python google-app-engine urllib2 urlfetch


    【解决方案1】:

    https://docs.python.org/2/library/urllib2.html

    urllib2.urlopen(url[, data][, timeout])
    

    可选的 timeout 参数指定超时时间(以秒为单位) 阻塞操作,如连接尝试(如果未指定,则 将使用全局默认超时设置)。

    【讨论】:

      【解决方案2】:

      按照 Paul 的建议,您可以传递 timeout 参数。在 App Engine 上,它与 URL 获取相关联,并将其最后期限调整为最多 60 秒。请记住,如果 urlopen 花费的时间超过 timeout 参数中指定的时间,您将收到来自 google.appengine.api.urlfetch_errors.DeadlineExceededError 的 DeadlineExceededError,而不是通常的 socket.timeout。捕获此错误并在必要时重试/记录是一个好习惯。有关处理 DeadlineExceededError 的更多信息,请参阅 [1]。

      [1] - https://developers.google.com/appengine/articles/deadlineexceedederrors

      【讨论】:

      • 你从哪里得到 10 秒的限制?我能找到的只有60秒。这是 gae 特有的,还是只是一个错字?
      • 打错字了,抱歉。限制为 60 秒/10 分钟(任务队列)。
      猜你喜欢
      • 1970-01-01
      • 2014-09-28
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多