4

在我的应用程序中,我使用 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我得到它的bcause服务器在指定的时间内没有响应,我们可以处理异常..am但不能这样做。任何帮助,将不胜感激。谢谢您的帮助

4

2 回答 2

12

URL Fetch 请求的默认超时时间仅为 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')

如果您始终发现超出它,请考虑使用异步请求或将逻辑移动到任务队列。

于 2011-06-23T12:03:42.377 回答
0

如您所说,发生错误是因为您没有及时得到响应,并且请求超过了截止日期。

您可以做的是将请求移动到任务队列中,因为任务可以运行更长的时间。

至于捕获异常,您是否尝试过在 self.redirect 之后添加 return 语句?

于 2011-06-23T11:10:55.013 回答