gpt4 book ai didi

python - 如何使用 python/listing docker images 获取 GCR 访问 token

转载 作者:行者123 更新时间:2023-12-02 08:21:33 25 4
gpt4 key购买 nike

我使用gcloud auth print-access-token获得的访问 token 显然与我通过一些基本Python代码获得的访问 token 不同:

export GOOGLE_APPLICATION_CREDENTIALS=/the-credentials.json
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
credentials.get_access_token()

我想做的是获得一个可以使用的 token :

curl -u _token:<mytoken> https://eu.gcr.io/v2/my-project/my-docker-image/tags/list

我不想安装 gcloud 实用程序作为我的应用程序的依赖项,因此我尝试通过 oath google 凭据以编程方式获取访问 token

最佳答案

我知道这是一个非常古老的问题,但我刚刚遇到 the exact same problem of requiring an ACCESS_TOKEN in Python and not being able to generate it ,并设法使其发挥作用。

您需要做的是使用变量credentials.token,但一旦您首次创建凭证对象,它就不会存在,并返回None。为了生成 token ,google.cloud 库必须使用凭据,在我的例子中,这是通过使用 googleapiclient.discovery.build 方法完成的:

sqladmin = googleapiclient.discovery.build('sqladmin', 'v1beta4', credentials=credentials)
response = sqladmin.instances().get(project=PROJECT_ID, instance=INSTANCE_ID).execute()
print(json.dumps(response))

之后可以使用正确生成 ACCESS_TOKEN

access_token = credentials.token

我还使用 google.cloud storage 作为测试凭据的方式对其进行了测试,并且只需尝试通过相应的 Python 库访问 GCS 中的存储桶即可,它也有效:

from google.oauth2 import service_account
from google.cloud import storage
PROJECT_ID = your_project_id_here
SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
try:
list(storage.Client(project=PROJECT_ID, credentials=credentials).bucket('random_bucket').list_blobs())
except:
print("Failed because no bucket exists named 'random_bucket' in your project... but that doesn't matter, what matters is that the library tried to use the credentials and in doing so generated an access_token, which is what we're interested in right now")

access_token = credentials.token
print(access_token)

关于python - 如何使用 python/listing docker images 获取 GCR 访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46450200/

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