使用 Python 3.4 的服务器到服务器应用程序的 OAuth 2.0,无法导入名称 'SERVICE_ACCOUNT'

OAuth 2.0 for Server to Server Applications using Python 3.4, cannot import name 'SERVICE_ACCOUNT'

我正在尝试在我的 Python 3.4 应用程序中实施 'Server to Server' OAuth 身份验证以与 Google 云存储一起使用。所以,一般来说,它是在这个页面上描述的 Using OAuth 2.0 for Server to Server Applications

但是当我 运行 我的脚本时出现错误:

Traceback (most recent call last):
File "my_script.py", line 4, in from oauth2client.service_account import ServiceAccountCredentials
File "/usr/local/lib/python3.4/dist-packages/oauth2client/service_account.py", line 31, in from oauth2client.client import SERVICE_ACCOUNT

ImportError: cannot import name 'SERVICE_ACCOUNT'

所以,这是我的代码:

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http

scopes = ['https://www.googleapis.com/auth/cloud-platform.read-only']

credentials = ServiceAccountCredentials.from_json_keyfile_name('./keyfile.json', scopes)

http_auth = credentials.authorize(Http())
service = build('storage', 'v1', http=http_auth)

如果你能帮助我,那就太好了!这是我第一个使用 Python 语言编写的脚本,我在 Python 和 Linux 世界中都是新手,所以我可能会错过一些非常明显的东西。

如果重要的话,我的OS是Ubuntu12.04.

谢谢!

好吧,不知何故它开始起作用了。抱歉,我知道自我回答不是很好,但我花了 2 天时间解决这个问题。

所以,正如我之前提到的,我是 Linux 世界中的新手。我认为,oauth2client 重新安装对我有帮助。我试图用 pip install -Iv oauth2client==1.5.2 将它降级到 1.5.2 版本,然后又一次失败 运行 pip install oauth2client --upgrade.

我还用 googleapiclient 替换了 apiclient 库,所以我的第一个字符串现在看起来像 from googleapiclient.discovery import build

现在可以用了,我什至不知道为什么。

抱歉再次自我回答。

我发现google-api-python-client安装了oauth2client1.5.2版本,但实际上需要2.0.0版本。所以,是你的 pip install oauth2client --upgrade 救了你。

我遇到了类似的问题,我遇到了 cannot import name xxxx 错误。事实证明,我的环境中有旧的 *.pyc 文件来自旧的 oauth2client 版本。即使我更新到最新的 oauth2client 版本,当我尝试 运行 时,*.pyc 文件仍在使用。我只是删除了 oauth2client *.pyc 文件,然后重新运行我的程序,没有任何问题。