Python 在谷歌应用程序引擎中使用urllib2;等待来自URL的HTTP响应时超过了截止日期:“…”;
我正在用python为Google应用程序引擎(GAE)使用urllib2。 应用程序经常因以下错误而崩溃: 等待来自URL的HTTP响应时超过了截止日期: 源代码如下所示:Python 在谷歌应用程序引擎中使用urllib2;等待来自URL的HTTP响应时超过了截止日期:“…”;,python,google-app-engine,urllib2,urlfetch,Python,Google App Engine,Urllib2,Urlfetch,我正在用python为Google应用程序引擎(GAE)使用urllib2。 应用程序经常因以下错误而崩溃: 等待来自URL的HTTP响应时超过了截止日期: 源代码如下所示: import webapp2 import urllib2 from bs4 import BeautifulSoup def functionRunning2To5Seconds_1() #Check if the Url could be parsed try: url
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
我发现这样说:
您可以使用Python标准库urllib、urllib2或httplib
发出HTTP请求。在App Engine中运行时,这些库
使用应用程序引擎的URL获取服务执行HTTP请求
这是:
您可以设置请求的截止日期,即请求的最长时间
服务将等待响应。默认情况下,获取的截止日期
是5秒。HTTP请求和请求的最大截止时间为60秒
60秒用于任务队列和cron作业请求
那我该怎么做呢?如何在urllib2上设置超时
或者,我必须重写整个应用程序才能使用应用程序引擎的URL获取服务吗
(附:有人知道一种安全的方法来并行运行“r_data1=functionRunning2To5Seconds_…()”调用吗?
可选的timeout参数指定的超时时间(以秒为单位)
阻塞操作,如连接尝试(如果未指定,则
将使用全局默认超时设置)
正如Paul所建议的,您可以传递timeout参数。在AppEngine上,它与URL获取绑定,并将其截止时间调整为最多60秒。请记住,如果urlopen占用的时间超过了timeout参数中指定的时间,您将从google.appengine.api.urlfetch_errors.DeadlineExceededError获得DeadlineExceededError,而不是通常的socket.timeout。捕获此错误并在必要时重试/记录是一种很好的做法。有关处理DeadLineExceeDerror的更多信息,请参见[1]
[1] -你从哪里得到10秒的限制?我能找到的只有60秒。这是gae特有的,还是只是一个打字错误?一个打字错误,对不起。限制为60秒/10分钟(任务队列)。
urllib2.urlopen(url[, data][, timeout])