DeadlineExceededError: 应用程序错误: 使用urllib2.urlopen()函数时出现5

4 投票
2 回答
2929 浏览
提问于 2025-04-16 20:08

在我的应用程序中,我使用了urllib2.urlopen()这个函数来调用一个API,并获取这个API的结果。但是这个方法有时候不太好用。有时候能得到结果,但有时候会出现以下错误:

Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 700, in __call__
handler.get(*groups)
  File "/base/data/home/apps/s~malware-app/7.351334968546050391/main.py", line 505, in get
f = urllib2.urlopen('http://whoapi.com/api-v1/?domain=%s&rtype=alexarank&apikey=xyz'% domain)
  File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 124, in urlopen
    return _opener.open(url, data)
  File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 381, in open
response = self._open(req, data)
  File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 399, in _open
  '_open', req)
  File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 360, in _call_chain
result = func(*args)
  File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 1114, in http_open
return self.do_open(httplib.HTTPConnection, req)
  File "/base/python_runtime/python_dist/lib/python2.5/urllib2.py", line 1087, in do_open
r = h.getresponse()
  File "/base/python_runtime/python_dist/lib/python2.5/httplib.py", line 197, in getresponse
self._allow_truncated, self._follow_redirects)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 260, in fetch
return rpc.get_result()
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 592, in get_result
return self.__get_result_hook(self)
  File "/base/python_runtime/python_lib/versions/1/google/appengine/api/urlfetch.py", line 364, in _get_fetch_result
raise DeadlineExceededError(str(err))
DeadlineExceededError: ApplicationError: 5 

我看到有人提到可以用try-except的方法来处理这个问题,但在我的代码中并没有奏效。我的代码块是:

 try:                      
   f = urllib2.urlopen('http://whoapi.com/api-v1/?domain=%s&rtype=serverip&apikey=xyzxyz'% domain)
   ip = f.read()
 except DeadlineExceededError, e:
   self.redirect('/error')

我导入了:

from google.appengine.runtime import DeadlineExceededError

从StackOverflow上我了解到,这个问题是因为服务器没有在规定的时间内响应,我们可以处理这个异常……但我还是没办法做到这一点。希望能得到一些帮助。非常感谢你的帮助!

2 个回答

0

正如你所说,这个错误发生是因为你没有及时收到回应,请求超出了时间限制。

你可以把这个请求放到一个任务队列里,因为任务可以运行更长的时间。

至于捕捉异常,你有没有试过在self.redirect之后加一个返回语句?

12

默认情况下,URL获取请求的超时时间只有5秒,所以你可能想通过直接使用urlfetch来增加这个时间:

from google.appengine.api import urlfetch

try:
    resp = urlfetch.fetch('http://whoapi.com/api-v1/?domain=%s&rtype=serverip&apikey=xyzxyz'% domain, method=urlfetch.GET, deadline=10)
    ip = r.content
except urlfetch.DownloadError:
    self.redirect('/error')

如果你发现经常超出这个时间,可以考虑使用异步请求,或者把逻辑放到任务队列中处理。

撰写回答