python - 使用 Cloud Scheduler 的 HTTP 触发 Cloud Function

标签 python google-cloud-functions google-cloud-scheduler

我的云函数在 Cloud Scheduler 中的作业有问题。我使用下一个参数创建了作业:

目标:HTTP

URL:我的云函数触发url

HTTP 方法:POST

正文:

{
 "expertsender": {
  "apiKey": "ExprtSender API key",
  "apiAddress": "ExpertSender APIv2 address",
  "date": "YYYY-MM-DD",
  "entities": [
     {
        "entity": "Messages"
     },
     {
        "entity": "Activities",
        "types":[
           "Subscriptions"
        ]
     }
  ]
 },
 "bq": {
         "project_id": "YOUR GCP PROJECT",
         "dataset_id": "YOUR DATASET NAME",
         "location": "US"
       } 
}

这个机构的实际值(value)已经改变。

当我运行这个作业时,我得到了一个错误。原因是POST请求的processing body导致的。

但是,当我使用这个主体并将其用作测试中的触发事件时,我没有收到任何错误。所以我认为,我的工作在 body 表现方面存在问题,但我不知道如何解决它。我会很高兴有任何想法。

最佳答案


免责声明: 我尝试使用 NodeJS 解决同样的问题,并且我能够得到解决方案


我知道这是一个老问题。但我觉得回答这个问题是值得的,因为我已经花了将近 2 个小时来找出这个问题的答案。

场景一:通过Cloud Scheduler触发Cloud Function

  • 函数无法读取请求正文中的消息。

场景二:通过云函数界面的测试标签触发云函数

  • 函数调用始终执行良好,没有错误。

我发现了什么?

  • 当 GCF 例程通过 Cloud Scheduler 执行时,它会将 header content-type 作为 application/octet-stream 发送。这使得express js在Cloud scheduler POST数据时无法解析request body中的数据。
  • 但是当使用完全相同的请求主体通过 Cloud Function 接口(interface)测试函数时,一切正常,因为接口(interface)上的Testing 功能发送 header content-typeapplication/json 和 express js 能够读取请求主体并将数据解析为 JSON 对象。

解决方案

我必须手动将请求主体解析为 JSON(明确使用基于内容类型 header 的 if 条件)以获取请求主体中的数据。

/**
 * Responds to any HTTP request.
 *
 * @param {!express:Request} req HTTP request context.
 * @param {!express:Response} res HTTP response context.
 */
exports.helloWorld = (req, res) => {
  let message = req.query.message || req.body.message || 'Hello World!';

  console.log('Headers from request: ' + JSON.stringify(req.headers));

  let parsedBody;

  if(req.header('content-type') === 'application/json') {
    console.log('request header content-type is application/json and auto parsing the req body as json');
    parsedBody = req.body; 
  } else {
    console.log('request header content-type is NOT application/json and MANUALLY parsing the req body as json');
    parsedBody = JSON.parse(req.body);
  }

  console.log('Message from parsed json body is:' + parsedBody.message);

  res.status(200).send(message);
};

这确实是 Google 必须解决的一个功能问题,希望 Google 能尽快修复它。

Cloud Scheduler - Content Type header issue

关于python - 使用 Cloud Scheduler 的 HTTP 触发 Cloud Function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216177/

相关文章:

google-cloud-platform - 如何调度经过身份验证的云函数的http调用?

python - 是否有模型类型可以在 django 中存储标签?

python - 获取从索引到结束的数组元素

exception - 谷歌云函数 "[ERROR]: Exception on/[POST]"

firebase - 依赖关系如何影响 Firebase Functions 冷启动?

javascript - 通过 Firebase Cloud 函数提取特定节点值

python - 无法执行 Cloud Function 触发不允许未经身份验证的调用的 HTTP 触发 Cloud Function?

python - 产品比价工具 : Difficulty in matching identical items

python - 类型错误 : classification_report() takes 2 positional arguments but 3 were given

谷歌云上的Python脚本调度