【问题标题】:Problem with HTTP trigger with Google Cloud FunctionGoogle Cloud Function 的 HTTP 触发器问题
【发布时间】:2020-08-31 00:09:41
【问题描述】:

这是我的代码

import json
from flask import escape
def location_sort(request):
    request_json = request.get_json()
    location = json.dumps(request_json)
    location = json.loads(location)
    reverse_location = {v: k for k, v in location.items()}


    x = location.keys()
    harf_x = (float(max(x)) + float(min(x))) / 2 

    y_right = []
    y_left = []
    sorted_location = [] 


    for i in location:
        if float(i) < harf_x:
            y_left.append(location[i])
        else: 
            y_right.append(location[i])

    y_left.sort() 
    y_right.sort(reverse=True) 

    sorted_input = y_left + y_right 


    for i in sorted_input:
        sorted_location.append([reverse_location[i], i])
    for i in sorted_location:
        i[0],i[1] = float(i[0]),float(i[1])
    return sorted_location

def cal_centroid(location):
    area = 0 # 면적
    centroid_x = 0 
    centroid_y = 0 
    temp = 0

    for i in range(len(location)):
        if i == len(location)-1: 
            temp = location[i][0]*location[0][1] - location[0][0]*location[i][1]
            area += temp*0.5
            centroid_x += (location[i][0] + location[0][0]) * temp
            centroid_y += (location[i][1] + location[0][1]) * temp
        else:
            temp = location[i][0]*location[i+1][1] - location[i+1][0]*location[i][1]
            area += temp*0.5
            centroid_x += (location[i][0] + location[i+1][0]) * temp
            centroid_y += (location[i][1] + location[i+1][1]) * temp

    centroid_x = round(centroid_x / (6*area), 6)
    centroid_y = round(centroid_y / (6*area), 6)
    x = [centroid_x, centroid_y]
    return json.dumps(x)

def main(request):
    a = location_sort(request)
    return cal_centroid(a)

我使用 main 运行我的代码。通过谷歌云功能上的测试代码,我可以使用触发事件框输入参数。但我想把参数放在使用 url 中。如下所示。

https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME?request={"37.284213":"127.006481","37.562045":"127.034809","37.528694":"126.907483","37.411124":"127.124356"}

我应该如何更改我的代码以使其行为如此?我很难理解有关 Google Functions 的 Google 文档。感谢您的帮助。

【问题讨论】:

    标签: python http google-cloud-platform triggers google-cloud-functions


    【解决方案1】:

    您需要使用请求正文中的 JSON 而不是 URL 参数来发出 POST 请求。例如,curl:

    curl -X POST https://YOUR_REGION-YOUR_PROJECT_ID.cloudfunctions.net/FUNCTION_NAME -H "Content-Type:application/json"  -d '{"37.284213":"127.006481","37.562045":"127.034809","37.528694":"126.907483","37.411124":"127.124356"}'
    

    【讨论】:

    • 如果我想使用 URL 参数,我该如何更改我的代码?我上传了另一个问题,对我的代码进行了一些更改。
    • 您的代码会解析 JSON POSTed body request.get_json()。取而代之的是,您必须获取 url arg,如 @DustinIngram 链接中所述:name = request.args.get('name')
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 2018-09-20
    • 2022-08-16
    相关资源
    最近更新 更多