无法在云函数中使用 gcp 云调度程序的 json 主体作为参数值?

Kau*_*ole 5 python-3.x google-bigquery google-cloud-functions serverless google-cloud-scheduler

我有一个云调度程序,我用它来触发我的云函数作为 http 调用,在我的云函数中,我想形成一个查询(应该是动态的)。为此,我从云调度程序(Json Body)传递了一些参数,但是当我触发我的云函数时,它不会将来自云调度程序的参数值作为 json 主体。谁能帮我解决这个问题。

来自云调度程序的 json 正文:

{ 
   "unit":"QA",
   "interval":"3"
}
Run Code Online (Sandbox Code Playgroud)

云函数代码:

def main(request):

    request_json = request.get_json(silent=True)
    request_args = request.args

    if request_json and 'unit' in request_json:
        retail_unit = request_json['unit']
    elif request_args and 'unit' in request_args:
        retail_unit = request_args['unit']
    else:
        unit = 'UAT'

    if request_json and 'interval' in request_json:
        interval = request_json['interval']
    elif request_args and 'interval' in request_args:
        interval = request_args['interval']
    else:
        interval = 1

    query = "select * from `myproject.mydataset.mytable` where unit='{}' and interval ={}".format(                                                                                                    
    unit,interval)
    client = bigquery.Client()
    job_config = bigquery.QueryJobConfig()
    dest_dataset = client.dataset(destination_dataset, destination_project)
    dest_table = dest_dataset.table(destination_table)
    job_config.destination = dest_table
    job_config.create_disposition = 'CREATE_IF_NEEDED'
    job_config.write_disposition = 'WRITE_APPEND'
    job = client.query(query, location='US', job_config=job_config)
    job.result()
Run Code Online (Sandbox Code Playgroud)

注意:当我从云调度程序传递相同的变量作为 http url ( https://my-region-test-project.cloudfunctions.net/mycloudfunction?unit=QA&interval=3 ) 中的参数值时,它会起作用

Voy*_*Voy 8

Content-Type您可以通过使用flag创建 cron 作业来覆盖默认值gcloud--headers Content-Type=application/json

例如:

gcloud scheduler jobs create http my_cron_job \
  --schedule="every 5 hours" \
  --uri="https://${ZONE}-${PROJECT_ID}.cloudfunctions.net/${FUNCTION_NAME}" \
  --http-method=POST \
  --message-body='{"foo": "bar"}' \
  --headers Content-Type=application/json
Run Code Online (Sandbox Code Playgroud)

GCP Console 级别似乎还无法提供此功能。更新08/2021:现在似乎已经在UI中实现了:

调度程序头


或者,force=True如果您使用 Flask,使用似乎会有所帮助:

gcloud scheduler jobs create http my_cron_job \
  --schedule="every 5 hours" \
  --uri="https://${ZONE}-${PROJECT_ID}.cloudfunctions.net/${FUNCTION_NAME}" \
  --http-method=POST \
  --message-body='{"foo": "bar"}' \
  --headers Content-Type=application/json
Run Code Online (Sandbox Code Playgroud)

这是因为 Cloud Scheduler 似乎将默认Content-Type标头设置为application/octet-stream. 请参阅文档


Pen*_*m10 3

最好的提示是UTF-8问题。

另请查看其他线程中描述的情况: HTTP Triggering Cloud Function with Cloud Scheduler