python + 谷歌表格 == gspread,但遗憾的是属性错误:类型对象"服务帐户凭据"没有属性"from_json_keyfile"



我正在尝试使用gspread库将谷歌表单与python连接起来。

我尝试过大量的gspread使用示例,但都没有成功。我也使用过同样失望和绝望的谷歌官方库(实际上,谷歌代码导致终端下的身份验证页面不起作用,"因为javascript在你的浏览器中没有启用")

我的示例代码:

import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile.name('client_secret.json', scope)
gc = gspread.authorize(credentials)
hoja = gc.open('testpy').sheet1
print(hoja.get_all_records())

client.secret.json是从服务帐户凭据中获得的secrey密钥json文件中重命名的。它有点像这个

{
"type": "service_account",
"project_id": "personaltestpygshee6",
"private_key_id": "29etcetc",
"private_key": "-----BEGIN PRIVATE KEY-----netcetcn-----END PRIVATE KEY-----n",
"client_email": "project@project.iam.gserviceaccount.com",
"client_id": 423etcetc",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/project%40project.iam.gserviceaccount.com"
}

当我运行脚本时,这是我获得的错误消息

File "5testgooshee.py", line 6, in <module>
credentials = ServiceAccountCredentials.from_json_keyfile.name('client_secret.json', scope)
AttributeError: type object 'ServiceAccountCredentials' has no attribute 'from_json_keyfile'

我发誓,我已经完成了家庭作业。蒸汽从我耳朵里冒出来。除了我的之外,我不知道问题出在哪里,为什么它在很多例子中都有效

故障在哪里?为什么我不能让它工作?

提前感谢

最后,这个问题有了一个(临时的?)解决方案。我们需要记住,OAuth2已被弃用,所有基于它的解决方案(如GSpread)都可能停止运行。

现在,解决方案:

  1. 正如@Tanaike所指出的,起点是服务帐户凭据调用中的一个拼写错误。需要指出的是,在一些教程中,它被拼写为ServiceAccountCredentials.from_json_keyfile.name('client_secret.json', scope),其中它应该是ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)。那里有一些教程可以复制这个拼写错误
  2. 此外,Windows还有另一个问题。您需要使用python安装PyOpenSSL。如果使用windows box或WSL,则需要安装完整版本的win32OpenSSL(来源:ImportError:无法导入名称SignedJwtAssertionCredentials)http://slproweb.com/products/Win32OpenSSL.html您需要在PyOpenSSL之前安装它。。。我发现您必须安装与python相同的版本,32位或64位。这听起来可能很傻,也可能很琐碎,但如果你不考虑,它就不会起作用

感谢大家抽出时间并回答

最新更新