如何从Python访问google cloud docker regystry

如何从Python访问google cloud docker regystry,python,gcloud,gcloud-python,dockerpy,google-cloud-python,Python,Gcloud,Gcloud Python,Dockerpy,Google Cloud Python,我想通过http API从Google Cloud Docker注册表检索图像列表 我在命令行中找到了这样一种方法: curl -u _token:$(gcloud auth print-access-token) https://gcr.io/v2/{project}/{repo}/tags/list 但是我想在Python中以编程的方式完成它。以下是我迄今为止所做的尝试: 下面的方法可以工作,但我无法找到一种不调用gcloudshell cmd就检索身份验证令牌的方法 import req

我想通过http API从Google Cloud Docker注册表检索图像列表

我在命令行中找到了这样一种方法:

curl -u _token:$(gcloud auth print-access-token) https://gcr.io/v2/{project}/{repo}/tags/list
但是我想在Python中以编程的方式完成它。以下是我迄今为止所做的尝试:

下面的方法可以工作,但我无法找到一种不调用
gcloud
shell cmd就检索身份验证令牌的方法

import requests
import subprocess

command = "gcloud auth print-access-token"
pswd= subprocess.check_output(command, shell=True).decode().strip()

repo = "repo"
project = "myproject"
user = "_token"
url = "https://gcr.io/v2/{project}/{repo}/tags/list".format(project=project, repo=repo)
r = requests.get(url, auth=(user, pswd))
print (r.status_code, r.headers['content-type'], r.encoding, r.text)
此外,我还尝试使用经过身份验证的httplib2执行请求:

import httplib2
from oauth2client.client import GoogleCredentials
http = httplib2.Http()
credentials = GoogleCredentials.get_application_default()

scopes = "https://www.googleapis.com/auth/cloud-platform"

credentials = credentials.create_scoped(scopes)

http = credentials.authorize(http)
print (http.request("https://gcr.io/v2/healthshield-dev/dl/tags/list"))
结果是
b'{“errors”:[{“code”:“UNAUTHORIZED”,“message”:“notauthorized.”}]}'


有人能和我分享一下他的经验吗?

我能够完成您在这里需要做的事情,但在Java中,翻译成Python应该相当简单。这就是我所做的:

  • 使用Google OAuth2 API Client Library for Java()获取用于对gcr.io/v2请求进行身份验证的令牌。在“其他”部分中,我为服务帐户使用了jsonKeyFile设置
  • Python客户端库->

  • 现在使用令牌,只需向
  • 请注意,使用curl-u时,您将凭据作为_token:value传递,因此需要将其编码到需要在请求中设置的基本身份验证头中。这就是我所做的(有点):


    希望这有帮助。

    我能够完成您在这里需要做的事情,但在Java中,翻译成Python应该相当简单。这就是我所做的:

  • 使用Google OAuth2 API Client Library for Java()获取用于对gcr.io/v2请求进行身份验证的令牌。在“其他”部分中,我为服务帐户使用了jsonKeyFile设置
  • Python客户端库->

  • 现在使用令牌,只需向
  • 请注意,使用curl-u时,您将凭据作为_token:value传递,因此需要将其编码到需要在请求中设置的基本身份验证头中。这就是我所做的(有点):

    希望这有帮助

            GoogleCredential credential = GoogleCredential.fromStream(keyFileInputStream).createScoped(Collections.singleton(ContainerScopes.CLOUD_PLATFORM));
    
            credential.refreshToken();
            String token = credential.getAccessToken();
    
    String encoding = Base64Encoder.encode("_token:"+token);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + encoding);