如何将身份验证/凭据传递给我从 Python 运行的谷歌云 API 帖子



我不知道如何将身份验证/凭据传递给我正在从我的 python 程序运行的谷歌云 API 帖子

import requests
api_endpoint = "https://dataflow.googleapis.com/v1b3/projects/projectid/templates"

data = {
"jobName": "scriptjob2",
"parameters": {
"inputFilePattern": "gs://bucket/files/*.json",
"outputTopic": "projects/project6/topics/data"
},
"environment": {
"tempLocation": "gs://bucket/tmp",
"zone": "us-central1-f"
},
"gcsPath": "gs://dataflow-templates/latest/GCS_Text_to_Cloud_PubSub",
"location": "us-central1"
}
r = requests.post(url = api_endpoint, data = data)
result = r.text
print("Result:%s"%result)

我知道我应该通过谷歌服务帐户身份验证,但我只是不知道该怎么做。这是我收到的错误消息。

"error": {
"code": 401,
"message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other v
alid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
"status": "UNAUTHENTICATED"
}
}

这就是我能够让它工作的方式:

from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials
credentials = GoogleCredentials.get_application_default()
service = build('dataflow', 'v1b3', credentials=credentials)

PROJECT = 'projectid'
BUCKET = 'dataflow-templates'
TEMPLATE = 'GCS_Text_to_Cloud_PubSub'
GCSPATH="gs://{bucket}/latest/{template}".format(bucket=BUCKET, template=TEMPLATE)
BODY = {
"jobName": "job1",
"parameters": {
"inputFilePattern": "gs://bucket/files/*.json",
"outputTopic": "projects/project6/topics/data"
},
"environment": {
"tempLocation": "gs://bucket/tmp",
"zone": "us-central1-f"
}
}

request = service.projects().templates().launch(projectId=PROJECT, gcsPath=GCSPATH, body=BODY)
response = request.execute()
print(response)

我的建议是将 sdk for python 用于数据流。

但是,如果您坚持使用请求,则非常简单:

"https://dataflow.googleapis.com/v1b3/projects/projectid/templates&key={yourapikey}"

这是浏览器中指向此内容的链接,供您进行测试。

最新更新