You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Python创建Cloud Tasks:自定义参数配置技术问询

任务队列与HTTP Target Task创建方案

需求概述

  • 队列接收period(整数)等参数,将其转换为指定结构的Task,多键参数按规则分组
  • 队列携带task和period调用Task Service
  • Task Service接收参数后,通过GCP客户端库创建HTTP Target Task

现有基础

  • Cloud Run上部署Flask应用作为任务API端点,负责验证请求并接收队列任务
  • 拥有嵌入式Python内部服务,可处理参数并输出队列所需参数集合
  • 已具备沙箱队列中创建任务的基础Python代码,掌握JSON payload添加方法

核心困惑

需明确如何将接收到的自定义参数(含多属性参数)整合为符合Schema的Task结构,并携带task与初始period参数调用Task Service完成HTTP Target Task的创建。

优化后的代码实现

以下是修正并完善后的代码,解决参数整合与payload构造问题:

"""Create a task for a given queue with structured payload."""

import datetime
import json

from google.cloud import tasks_v2
from google.protobuf import duration_pb2, timestamp_pb2

# 示例输入参数(实际应从内部服务接收)
period = 3600  # 示例周期,单位秒
operation = {
    "result_type": "update",
    "detail": {"action": "restart"}
}
resource = {
    "type": "compute_instance",
    "resource_id": 12345,
    "project_id": "my-gcp-project",
    "zone": "us-central1-a"
}
event = "instance_state_change"

# 构造符合JSON Schema的Task结构,包含period和task
task_payload = {
    "task": {
        "operation": operation,
        "event": event,
        "resource": resource
    },
    "period": period
}

# 初始化Cloud Tasks客户端
client = tasks_v2.CloudTasksClient()

# 配置GCP资源信息(需替换为实际值)
project = "your-gcp-project-id"
queue = "your-queue-name"
location = "us-central1"
url = "https://your-cloud-run-service-url/task-endpoint"  # Cloud Run的Task端点URL
in_seconds = 180  # 任务延迟执行时间
task_name = f"task-{datetime.datetime.utcnow().strftime('%Y%m%d%H%M%S')}"  # 生成唯一任务名
deadline = 900

# 构造队列的完整路径
parent = client.queue_path(project, location, queue)

# 构建HTTP任务请求体
task = {
    "http_request": {
        "http_method": tasks_v2.HttpMethod.POST,
        "url": url,
        "headers": {"Content-type": "application/json"}
    }
}

# 处理payload:转为JSON字符串并编码为字节
payload_json = json.dumps(task_payload)
task["http_request"]["body"] = payload_json.encode()

# 设置任务调度时间
if in_seconds is not None:
    schedule_time = datetime.datetime.utcnow() + datetime.timedelta(seconds=in_seconds)
    timestamp = timestamp_pb2.Timestamp()
    timestamp.FromDatetime(schedule_time)
    task["schedule_time"] = timestamp

# 设置任务名称
if task_name is not None:
    task["name"] = client.task_path(project, location, queue, task_name)

# 设置任务调度超时
if deadline is not None:
    duration = duration_pb2.Duration()
    duration.FromSeconds(deadline)
    task["dispatch_deadline"] = duration

# 创建任务
response = client.create_task(request={"parent": parent, "task": task})
print(f"Created task {response.name}")

对应的JSON Schema

{
    "title": "TaskRequest",
    "description": "请求Task Service的payload结构",
    "type": "object",
    "properties": {
        "period": {
            "type": "integer",
            "description": "任务周期(秒)"
        },
        "task": {
            "title": "Task",
            "type": "object",
            "properties": {
                "event": {
                    "type": "string"
                },
                "resource": {
                    "type": "object",
                    "properties": {
                        "type": {"type": "string"},
                        "resource_id": {"type": "number"},
                        "project_id": {"type": "string"},
                        "zone": {"type": "string"}
                    },
                    "required": ["type", "resource_id", "project_id", "zone"]
                },
                "operation": {
                    "type": "object",
                    "properties": {
                        "result_type": {"type": "string"},
                        "detail": {"type": "object"}
                    },
                    "required": ["result_type", "detail"]
                }
            },
            "required": ["event", "resource", "operation"]
        }
    },
    "required": ["period", "task"]
}

关键说明

  1. 参数整合:将operation、resource、event直接映射到task字段下,同时保留period作为顶层参数,确保payload符合结构要求
  2. 任务唯一性:通过当前时间戳生成唯一任务名,避免重复创建
  3. 请求头设置:显式指定Content-type: application/json,确保Cloud Run端点能正确解析payload
  4. 类型校验:实际使用时可结合jsonschema库对输入参数进行校验,确保符合Schema规范

内容的提问来源于stack exchange,提问作者pynoobatbest

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 19:18:19