【问题标题】:AppEngine's urlfetch, how to force timeout to be respectedAppEngine的urlfetch,如何强制超时被尊重
【发布时间】:2017-03-28 15:02:44
【问题描述】:

我正在使用来自 Google Appengine 的 Urlfetch,并添加了截止日期参数以强制截止日期较短(3 秒),如下所示:

try:
    urlfetch.set_default_fetch_deadline(3)
    return urlfetch.fetch(url='http://www.example.com', method=urlfetch.GET, deadline=3)
except google.appengine.runtime.apiproxy_errors.DeadlineExceededError:
    pass
except google.appengine.api.urlfetch_errors.DeadlineExceededError:
    pass

return None

但无论如何,我的线程会持续运行 60 秒(Appengine 上 http 请求的最大执行时间),然后在 DeadlineException(“线程在请求​​后运行。”)上惨遭失败。

有没有办法保证上层查询在3秒内严格停止?

【问题讨论】:

  • 您确定异常实际上并未引发,而是被您的代码捕获并忽略了吗?也许尝试用一些logging 调用替换pass 语句来检查?
  • 我相信set_default_fetch_deadline() 适用于您使用rpcurlfetch.make_fetch_call() 时。你的urlfetch.fetch(...deadline=3) 应该足够了。尝试添加一个通用的except: 并在其中登录以及另一个excepts
  • 显然,deadline 参数已被完全删除,现在需要使用set_default_fetch_deadline。请参阅文档:cloud.google.com/appengine/docs/standard/python/…
  • 我已经用 logging.exception('{the name of the exception}') 替换了“pass”,我得到了 google.appengine.api.urlfetch_errors.DeadlineExceededError 一个。但奇怪的是,代码显然卡在这里,就像 logging.exception 在 600 秒后(在队列上)引发异常一样。根本不是这样!
  • 我进步了一点,但仍然坚持这一点。我发现异常首先在 3 秒(我的截止日期)后引发,然后代码挂在我添加的 logging.info 上,直到达到最大限制(在我的情况下为 600 秒)。为什么?我不知道!

标签: google-app-engine urlfetch


【解决方案1】:

我可以分享一些我目前在我的一个生产项目中运行的代码。在这个例子中,我使用了 0.5 秒的最后期限。最后我检查了一下,它还在工作:

t_rpc = urlfetch.create_rpc(deadline=0.5)
urlfetch.make_fetch_call(t_rpc, url)
# and then later...
try:
    result = t_rpc.get_result()
except:
    # handle errors...
    pass

# use the result...

这实际上是在使用 API 的异步版本,因此从技术上讲,您可以在调用 make_fetch_callget_result 之间进行操作。否则,您可以背靠背调用它们,它的功能与同步 API 相同。

【讨论】:

  • 谢谢你的代码,我试试看。我打算使用异步方法来调用 url,我不介意得到结果。你认为我从不打电话给rpc.get_result()可以吗?或者这会导致一些内存泄漏?
  • 你的代码很好用,我的原始代码也很好用。问题出在 Sentry 上,这是一个跟踪错误的服务,导致了这个问题!
猜你喜欢
  • 2015-05-06
  • 2020-02-02
  • 1970-01-01
  • 2010-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 2012-10-30
相关资源
最近更新 更多