gpt4 book ai didi

authorization - 无法获得服务帐户授权以使用 Python 客户端库 API 处理 GCS 脚本

转载 作者:行者123 更新时间:2023-12-01 02:30:04 26 4
gpt4 key购买 nike

在尝试编写 python 脚本以使用基于服务的授权访问 GCS 时,我想出了以下内容。请注意,'key' 是我的 p12 文件的内容。

我正在尝试仅读取我帐户中的存储桶列表。我已经使用 GCS 的 Web 界面成功创建了一个存储桶,并且可以使用 gsutil 看到它。

当我执行下面的代码时,出现 403 错误。起初我以为我没有被正确授权,但我从这个非常有用的网页(使用基于网络的授权)进行了尝试,并且它可以正常工作。 https://developers.google.com/apis-explorer/#p/storage/v1beta1/storage.buckets.list?projectId= &_h=2&

当我查看标题和查询字符串并将它们与网站生成的请求的 keaders 和查询进行比较时,我看到没有授权标题,并且查询字符串中没有 key= 标记。我想我认为凭证授权会为我解决这个问题。

我究竟做错了什么?

代码:

credentials = SignedJwtAssertionCredentials(
'xxx-my-long-email-from-the-console@developer.gserviceaccount.com',
key,
scope='https://www.googleapis.com/auth/devstorage.full_control')
http = httplib2.Http()
http = credentials.authorize(http)

service = build("storage", "v1beta1", http=http)

# Build the request

request = service.buckets().list(projectId="159910083329")

# Diagnostic

pprint.pprint(request.headers)
pprint.pprint(request.to_json())

# Do it!

response = request.execute()

当我尝试执行时,我得到了 403。

最佳答案

我得到了这个工作,但是,我使用的代码与您发布的代码段没有根本的不同。以防万一您想将我的版本与您的版本进行比较,下面附上了一个对我有用的 Python 程序的完整副本。我最初得到 403,就像你一样,这是由于继承了你的项目 ID :)。更新该值以使用我的项目 ID 后,我得到了正确的存储桶列表。要检查的两件事:

  • 确保您使用的项目 ID 正确,并且在 Google Developer Console 的“服务”选项卡上启用了“Google Cloud Storage JSON API”(这是与其他 Google Cloud Storage API 不同的服务)。
  • 确保您加载的服务帐户私钥与来自开发人员控制台的完全一样。我建议从您下载的文件中将其读入内存,就像我在这里所做的那样,而不是尝试将其复制到代码中的字符串中。

  • #!/usr/bin/env python

    import pprint
    import oauth2client
    from oauth2client.client import SignedJwtAssertionCredentials
    import httplib2
    from apiclient.discovery import build

    f = open('key.p12', 'r')
    key = f.read()
    f.close()

    credentials = SignedJwtAssertionCredentials(
    'REDACTED',
    key,
    scope='https://www.googleapis.com/auth/devstorage.full_control')
    http = httplib2.Http()
    http = credentials.authorize(http)

    service = build("storage", "v1beta1", http=http)

    # Build the request

    request = service.buckets().list(projectId="REDACTED")

    # Diagnostic

    pprint.pprint(request.headers)
    pprint.pprint(request.to_json())

    # Do it!

    response = request.execute()
    pprint.pprint(response)

    关于authorization - 无法获得服务帐户授权以使用 Python 客户端库 API 处理 GCS 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13694811/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com