【发布时间】:2014-09-23 07:43:17
【问题描述】:
我在 python 中将 urllib2 用于 Google App Engine (GAE)。 应用程序经常因为以下错误而崩溃:
等待来自 URL 的 HTTP 响应时超过了最后期限:....
源代码如下所示:
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
我发现了这个doc,它声明:
您可以使用 Python 标准库 urllib、urllib2 或 httplib 发出 HTTP 请求。在 App Engine 中运行时,这些库 使用 App Engine 的 URL 获取服务执行 HTTP 请求
还有这个:
您可以为请求设置截止日期,即最长时间 服务将等待响应。默认情况下,获取的截止日期 是 5 秒。 HTTP 请求的最大截止时间为 60 秒,并且 任务队列和 cron 作业请求为 60 秒。
那么我该怎么做呢?如何在 urllib2 上设置超时时间?
或者,我是否必须重写整个应用程序才能使用 App Engine 的 URL 获取服务?
(PS:有人知道并行运行“r_data1 = functionRunning2To5Seconds_...()”调用的安全方法吗?)
【问题讨论】:
标签: python google-app-engine urllib2 urlfetch