HTTP Triggering Cloud Function with Cloud Scheduler

后端 未结 3 2017
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 18:42

I have a problem with a job in the Cloud Scheduler for my cloud function. I created the job with next parameters:

Target: HTTP

URL

3条回答
  •  孤街浪徒
    2021-02-13 19:25

    Thank you @Dinesh for pointing towards the request headers as a solution! For all those who still wander and are lost, the code in python 3.7.4:

    import json
    
    raw_request_data = request.data
    
    # Luckily it's at least UTF-8 encoded...
    string_request_data = raw_request_data.decode("utf-8")
    request_json: dict = json.loads(string_request_data)
    

    Totally agree, this is sub-par from a usability perspective. Having the testing utility pass a JSON and the cloud scheduler posting an "application/octet-stream" is incredibly irresponsibly designed. You should, however, create a request handler, if you want to invoke the function in a different way:

    def request_handler(request):
        # This works if the request comes in from 
        # requests.post("cloud-function-etc", json={"key":"value"})
        # or if the Cloud Function test was used
        request_json = request.get_json()
        if request_json:
            return request_json
    
        # That's the hard way, i.e. Google Cloud Scheduler sending its JSON payload as octet-stream
        if not request_json and request.headers.get("Content-Type") == "application/octet-stream":
            raw_request_data = request.data
            string_request_data = raw_request_data.decode("utf-8")
            request_json: dict = json.loads(string_request_data)
    
        if request_json:
            return request_json
    
        # Error code is obviously up to you
        else:
            return "500"
    

提交回复
热议问题