ImportError:无法导入名称 SignedJwtAssertionCredentials

python

1个回答

写回答

lxq520

2025-06-21 18:55

+ 关注

Google
Google

使用 Google Cloud Platform 开发应用程序时,我们经常需要使用服务账号来进行身份验证和授权。Google Cloud Platform 提供了一个非常方便的 PythonGoogle-auth 来处理身份验证和授权的问题。然而,有时候在使用 Google-auth 库时可能会遇到一些问题,比如 ImportError: cannot import name 'SignedJwtAssertionCredentials' 错误。本文将介绍这个错误的原因以及解决方法,并提供一个案例代码来演示如何正确地使用 Google-auth 库。

## 错误原因

ImportError: cannot import name 'SignedJwtAssertionCredentials' 错误通常是因为 Google-auth 库的版本问题导致的。在较新的 Google-auth 版本中,SignedJwtAssertionCredentials 类已被弃用并从库中移除。取而代之的是 Google.oauth2.service_account 模块中的 Credentials 类。因此,当我们尝试导入 SignedJwtAssertionCredentials 类时,就会出现这个错误。

## 解决方法

要解决这个错误,我们需要更新我们的代码以适应最新版本的 Google-auth 库。我们可以使用 Google.oauth2.service_account 模块中的 Credentials 类来代替 SignedJwtAssertionCredentials 类。Credentials 类提供了一种更简洁和灵活的方式来创建身份验证凭据。

下面是一个简单的示例代码,演示了如何使用最新版本的 Google-auth 库来创建服务账号的身份验证凭据:

Python

from Google.oauth2 import service_account

from Googleapiclient.discovery import build

# 读取服务账号的 JSON 密钥文件

credentials = service_account.Credentials.from_service_account_file(

'path/to/service_account.JSon',

scopes=['Googleapis.com/auth/cloud-platform']">https://www.Googleapis.com/auth/cloud-platform']</a>

)

# 创建一个 Cloud Storage 的客户端

storage_client = build('storage', 'v1', credentials=credentials)

# 使用 Cloud Storage 客户端进行其他操作

buckets = storage_client.buckets().list().execute()

for bucket in buckets['items']:

print(bucket['name'])

在这个示例代码中,我们首先使用 service_account.Credentials.from_service_account_file 方法读取服务账号的 JSON 密钥文件,并指定了所需的授权范围。然后,我们使用 build 方法创建了一个 Cloud Storage 的客户端,并使用该客户端进行其他操作,比如列出存储桶的名称。

##

在使用 Google-auth 库时,如果遇到 ImportError: cannot import name 'SignedJwtAssertionCredentials' 错误,我们应该检查我们使用的 Google-auth 库的版本,并更新代码以适应最新版本的库。使用 Google.oauth2.service_account 模块中的 Credentials 类来代替 SignedJwtAssertionCredentials 类,并根据需要配置身份验证凭据的参数。这样,我们就可以顺利使用服务账号进行身份验证和授权了。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号