问题描述
我正在尝试使用 Python 客户端 google-cloud-tasks==2.1.0
使用 Google Cloud Tasks 创建任务,但我收到一个异常,要求 HttpRequest.url 是必需的。我正在设置相对 url,它是处理我的应用程序中任务的 URL。
队列存在并已使用以下方法创建:
gcloud task create queue notifications
代码:
client = tasks_v2.CloudTasksClient()
parent = client.queue_path(project,location,queue)
task = {
'app_engine_HTTP_Request': {
'http_method': tasks_v2.HttpMethod.POST,'relative_uri': notification_url,'body': payload.encode('utf-8')
},'HTTP_Request': {
'headers': {"Content-type": "application/json"}
}
}
response = client.create_task(parent=parent,task=task)
我收到的确切错误是:
google.api_core.exceptions.InvalidArgument: 400 HttpRequest.url is required
我正在尝试在我的 App Engine 标准环境中创建任务。
解决方法
@Donald 是对的,但我认为他链接的谷歌文档中有一个错字。我将标题设置在 app_engine_http_request
内,而不是 http_request
。
我认为您不能同时提供 app_engine_http_request
和 http_request
,您只能提供一个。像这样:
client = tasks_v2.CloudTasksClient()
parent = client.queue_path(project,location,queue)
task = {
'app_engine_http_request': {
'http_method': tasks_v2.HttpMethod.POST,'relative_uri': notification_url,'headers': {
'Content-Type': 'application/json'
},'body': payload.encode('utf-8')
}
}
response = client.create_task(parent=parent,task=task)
,
您的任务有两个目标,即 App Engine 和 HTTP。在 HTTP 上,需要 creating HTTP target tasks 中指定的 URL。
网址必须以“http://”或“https://”开头。要解决此问题,请更新您的 http_request
:
'http_request': {
'headers': {"Content-type": "application/json"},'url': "https://[SERVICE-URL]" + notification_url
}
或者,删除 http_request
并在声明任务后像这样指定标题:
task["http_request"]["headers"] = {"Content-type": "application/json"}
EDIT:指定 App Engine 标头时,也可以这样写:
task["app_engine_http_request"]["headers"] = {"Content-type": "application/json"}