【问题标题】:Make requests to Google API with Python使用 Python 向 Google API 发出请求
【发布时间】:2022-01-12 02:36:59
【问题描述】:

我正在尝试向 Google API 发出请求,以使用服务帐户和他的 JSON 密钥文件创建源存储库。 由于该产品没有客户端库,因此我使用 Python 使用此文档进行查询 https://cloud.google.com/source-repositories/docs/reference/rest

我已经使用类似的代码成功调用了我的云功能,但这次我在 401 错误时阻止了这些请求。我使用我的服务帐户的 JSON 设置了 GOOGLE_APPLICATION_CREDENTIALS,为服务帐户授予 Source Repository Administrator 的权限,但仍然返回 401。

这是我的代码

import urllib.request
import json
import urllib
import google.auth.transport.requests
import google.oauth2.id_token

body = { "name" : "projects/$my_project_name/repos/$name_repo"}
jsondata = json.dumps(body).encode("utf8")
req = urllib.request.Request('https://sourcerepo.googleapis.com/v1/projects/$my_project_name/repos')
req.add_header('Content-Type', 'application/json; charset=utf-8')

auth_req = google.auth.transport.requests.Request()
id_token = google.oauth2.id_token.fetch_id_token(auth_req, 'https://www.googleapis.com/auth/cloud-platform')
req.add_header("Authorization", f"Bearer {id_token}")
response = urllib.request.urlopen(req, jsondata)
print (response.read().decode())

我也尝试在这样的网址末尾使用 API-KEY

req = urllib.request.Request('https://sourcerepo.googleapis.com/v1/projects/$my_project_name/repos?key=$my-api-key')

谢谢

【问题讨论】:

    标签: python-3.x google-cloud-platform google-cloud-source-repos


    【解决方案1】:

    我也尝试在这样的网址末尾使用 API-KEY

    不支持 API 密钥。

    您的代码使用的是 OIDC 身份令牌而不是 OAuth 访问令牌。

    from google.oauth2 import service_account
    
    credentials = service_account.Credentials.from_service_account_file(
        '/path/to/key.json',
        scopes=['https://www.googleapis.com/auth/cloud-platform'])
    
    
    request = google.auth.transport.requests.Request()
    credentials.refresh(request)
    

    // 使用以下代码添加访问令牌:

    req.add_header("Authorization", f"Bearer {credentials.token}")
    

    【讨论】:

    • 完美运行。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-16
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多