python - 为什么我从 App Engine 调用 Google API 时会收到 invalid_grant?

标签 python google-app-engine

我正在尝试从 App Engine 访问 Google Prediction API,并按照此处的说明进行操作 -- https://developers.google.com/appengine/articles/prediction_service_accounts

部署在 App Engine 上时效果非常好。然而,相同的代码在本地开发服务器上失败并出现以下错误。

credentials = AppAssertionCredentials(
              scope='https://www.googleapis.com/auth/prediction')
http = credentials.authorize(httplib2.Http(memcache))
service = build("prediction", "v1.5", http=http, developerKey=api_key)

ERROR    2012-12-28 03:48:53,084 client.py:461] Failed to retrieve access token: {
  "error" : "invalid_grant"
}
ERROR    2012-12-28 03:48:53,115 cgi.py:121] Traceback (most recent call last):
  File "/Users/gkedia/git/thirdgaze/main.py", line 83, in <module>
    service = build('prediction', 'v1.5', http=http, developerKey=api_key)
  File "/Users/gkedia/git/thirdgaze/apiclient/discovery.py", line 175, in build
    resp, content = http.request(requested_url)
  File "/Users/gkedia/git/thirdgaze/oauth2client/client.py", line 503, in new_request
    self._refresh(request_orig)
  File "/Users/gkedia/git/thirdgaze/oauth2client/client.py", line 412, in _refresh
    self._do_refresh_request(http_request)
  File "/Users/gkedia/git/thirdgaze/oauth2client/client.py", line 472, in _do_refresh_request
    raise AccessTokenRefreshError(error_msg)
AccessTokenRefreshError: invalid_grant

我注意到的一件事是,对于完全相同的参数,key_name,signature = app_identity.sign_blob(base_str) 在生产环境和本地计算机上返回不同的签名。

我的计算机时间已正确同步,并且offline_access参数似乎尚未涉及。

最佳答案

app_identity 以及更常见的服务帐户无法在 dev_appserver 上运行,您必须回退常规 oauth2 webserver flow以便在本地测试时获取与常规 Google 帐户关联的访问 token 。

类似于:

flow = OAuth2WebServerFlow(client_id='your_client_id',
                           client_secret='your_client_secret',
                           scope='https://www.googleapis.com/auth/prediction',
                           redirect_uri='http://localhost:8080/oauth2callback')
self.redirect(flow.step1_get_authorize_url())

然后在 /oauth2callback 处理程序中:

credentials = flow.step2_exchange(self.request.get('code'))
http = credentials.authorize(httplib2.Http(memcache))
service = build("prediction", "v1.5", http=http, developerKey=api_key)

您可以使用 SERVER_SOFTWARE 轻松检测您是在 dev_appserver 上运行还是在生产环境中运行 environment variable .

关于python - 为什么我从 App Engine 调用 Google API 时会收到 invalid_grant?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064630/

相关文章:

python - 类在 Django 中没有 'objects' 成员

python - 获取上一行的值并计算新列 pandas python

python - 是否有访问列表的 "get or default"方式?

python - 仅从 App Engine 中的 ReferenceProperty 获取 Key/id

java - 在 App Engine 上使用 Java 中的 Python 代码

android - Google Cloud Endpoint - 项目运行后端配置时出错

java - 从 Android 应用程序的 Google App Engine 后端按实体 ID 获取实体时出错

Python:将奇怪的字典转换为 Pandas - 数据框

python - 使用重复嵌套模式从文本文件中提取文本

google-app-engine - 部署到 App Engine : Verifying availability