Python AppEngine使用Google Url Shortener API时:HTTPError: HTTP Error 403: Forbidden
我在使用Google的短网址API时遇到了一些麻烦,特别是在AppEngine的生产环境中。首先,我在开发者控制台里已经开启了短网址API,并且也开启了oAuth 2。此外,我还从API访问页面获取了一个简单的API访问浏览器密钥。
问题是,当我运行以下代码时,开发者控制台的日志里显示“HTTPError: HTTP Error 403: Forbidden”。有趣的是,使用相同的代码在开发环境中却能正常返回短网址。
def goo_shorten_url(url):
post_url = 'https://www.googleapis.com/urlshortener/v1/url?fields=id'
logging.info('post_url: {}'.format(post_url))
postdata = {'longUrl':url}
headers = {'Content-Type':'application/json'}
req = urllib2.Request(
post_url,
json.dumps(postdata),
headers
)
ret = urllib2.urlopen(req).read()
print ret
return json.loads(ret)['id']
如果我在POST请求的URL中包含API密钥,如下所示,
post_url = 'https://www.googleapis.com/urlshortener/v1/url?fields=id&key=MYAPIKEY'
那么在生产和开发环境中都返回HTTP Error 403。
我怀疑以下三种情况中有一种是对的,但我想听听大家的看法。
需要一个API密钥,但我使用的密钥不对。
不需要API密钥(这也解释了为什么在开发环境中不使用密钥也能工作),但我的API密钥错误,导致生产和开发环境都失败。
Google不允许应用程序以编程方式向其短网址API提交POST请求。(这并不能解释为什么在开发环境中会正常工作)
谢谢你的阅读。
生产环境
文件 "/base/data/home/apps/s~myapp/1.377367579804576653/util/test_module.py",第50行,调用了get函数 strin = goo_shorten_url(longurl) 文件 "/base/data/home/apps/s~myapp/1.377367579804576653/util/JOTools.py",第41行,调用了goo_shorten_url函数 ret = urllib2.urlopen(req).read() 文件 "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py",第127行,调用了urlopen return _opener.open(url, data, timeout) 文件 "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py",第410行,调用了open response = meth(req, response) 文件 "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py",第523行,调用了http_response 'http', request, response, code, msg, hdrs) 文件 "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py",第448行,调用了error return self._call_chain(*args) 文件 "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py",第382行,调用了_call_chain result = func(*args) 文件 "/base/data/home/runtimes/python27/python27_dist/lib/python2.7/urllib2.py",第531行,调用了http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden
开发环境(带API密钥)
文件 "C:_dev\eclipse-work\gae\MyProj\util\test_module.py",第50行,调用了get函数 strin = goo_shorten_url(longurl) 文件 "C:_dev\eclipse-work\gae\MyProj\util\JOTools.py",第41行,调用了goo_shorten_url函数 ret = urllib2.urlopen(req).read() 文件 "C:\PYTHON27\lib\urllib2.py",第127行,调用了urlopen return _opener.open(url, data, timeout) 文件 "C:\PYTHON27\lib\urllib2.py",第410行,调用了open response = meth(req, response) 文件 "C:\PYTHON27\lib\urllib2.py",第523行,调用了http_response 'http', request, response, code, msg, hdrs) 文件 "C:\PYTHON27\lib\urllib2.py",第448行,调用了error return self._call_chain(*args) 文件 "C:\PYTHON27\lib\urllib2.py",第382行,调用了_call_chain result = func(*args) 文件 "C:\PYTHON27\lib\urllib2.py",第531行,调用了http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 403: Forbidden