python - GAE 上的 Flask - 连接到 Google API - 无法使用 JSON 文件

标签 python google-app-engine flask google-api

我对 Flask、GAE 和 API 的使用相当陌生。我正在尝试构建一个可以连接到 Google API 之一的基本 Web 应用程序。

我的文件夹结构如下所示(我将其保存在主文件中):
应用程序网络情绪:
-app.yaml
-main.py
-lib
--sentimentanalysis.py
-静态
--credential.json

一切正常,但为凭据提供 json 文件。我的理解是有几种方法可以做到这一点:
1) 将 GOOGLE_APPLICATION_CREDENTIALS 环境变量设置为我在 app.yaml 中的文件目标
2)通过我的脚本(sentimentanalysis.py)请求文件

不幸的是,我无法完成这些工作。

选项 1):
在 app.yaml 我有一行:

env_variables:
   GOOGLE_APPLICATION_CREDENTIALS: static/key/credentials.json

然后我通过 dev_appserver.py 运行我的代码。并得到以下错误:

ApplicationDefaultCredentialsError: File static/key/credentials.json (pointed by GOOGLE_APPLICATION_CREDENTIALS environment variable) does not exist!

选项 2): 我的脚本 sentimentanalysis.py 中有一行代码:

  scope = ['https://www.googleapis.com/auth/cloud-platform']
  credentials = ServiceAccountCredentials.from_json_keyfile_name('/static/credentials.json', scope)

运行代码时出现以下错误:

    raise IOError(errno.EACCES, 'file not accessible', filename)
IOError: [Errno 13] file not accessible: '/static/credentials.json'
INFO     2016-08-06 04:10:51,678 module.py:788] default: "POST /Sentiment-analysis HTTP/1.1" 500 -

问题:
所以看起来无论我使用哪种方法,我都无法提供 JSON 文件的正确路径

我的问题是首先要知道以上任何选项是否正确,如果是,我做错了什么?如果它们不是正确的选择,您会推荐什么?

如果有人问过这个问题,我深表歉意,我已经尝试了几个小时来寻找答案,但一直无法破解...

谢谢!

最佳答案

如果您在 Google App Engine 上运行,那么您的代码会自动拥有所需的凭据。不要设置 GOOGLE_APPLICATION_CREDENTIALS,也不要调用 .from_json_keyfile_name。相反,调用:

credentials = GoogleCredentials.get_application_default()

如图所示: https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/api/getting_started.py

关于python - GAE 上的 Flask - 连接到 Google API - 无法使用 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38800487/

相关文章:

java - 谷歌应用引擎和 mongodb

google-app-engine - "ImportError: No module named _ssl"来自 Google App Engine 的 dev_appserver.py

python - 多对多使用 Flask-SQLAlchemy 返回原始 sql 而不是执行

Python uwsgi w/virtualenv --no-site-packages -- import site = AttributeError {'userbase' }

google-app-engine - 如何修复 "` 必须为自定义运行时设置 --custom_entrypoint 标志?

python - 用字典列表中找到的名称替换字典中的键 PYTHON-FLASK

python - 未下载 CSS 文件 - Flask

python - 如何转义 Python 字符串中的任何特殊 shell 字符?

python - 给定深度的不同递归函数

python - 使用 __set__ 获得类级别类型描述符的方法