我将此代码放在Google App Engine程序的顶部:
from google.appengine.api import urlfetch
urlfetch.set_default_fetch_deadline(60)
我正在使用开启器加载东西:
cj = CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor( cj ) )
opener.addheaders = [ ( 'User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64)' ) ]
resp = opener.open( 'http://www.example.com/' )
5秒后抛出异常:
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 1222, in https_open
return self.do_open(httplib.HTTPSConnection, req)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py", line 1187, in do_open
r = h.getresponse(buffering=True)
File "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/gae_override/httplib.py", line 524, in getresponse
raise HTTPException(str(e))
HTTPException: Deadline exceeded while waiting for HTTP response from URL: http://www.example.com
如何避免错误?
答案 0 :(得分:1)
您是否尝试在.open()
来电时设置超时?
resp = opener.open('http://example.com', None, 60)
如果达到set_default_fetch_deadline
指定的超时,Python将抛出DownloadError
或DeadlineExceededErrors
例外:https://cloud.google.com/appengine/docs/python/urlfetch/exceptions
答案 1 :(得分:0)
您还可以修补httplib2库并将截止日期设置为60秒
httplib2/__init__.py:
def fixed_fetch(url, payload=None, method="GET", headers={},
allow_truncated=False, follow_redirects=True,
deadline=60):
return fetch(url, payload=payload, method=method, headers=headers,
allow_truncated=allow_truncated,
follow_redirects=follow_redirects, deadline=60,
validate_certificate=validate_certificate)
return fixed_fetch
这是一个解决方法。