【发布时间】:2021-08-22 19:09:23
【问题描述】:
我想弄清楚如何在 GCP 云函数中解析 URL 参数。我正在尝试做这个answer 所做的事情。由于HTTP GCP cloud function 的入口点接受请求AFAIK。我可以想办法让 Flask 像我提到的示例中那样解析 URL 参数。
【问题讨论】:
标签: google-cloud-platform google-cloud-functions
我想弄清楚如何在 GCP 云函数中解析 URL 参数。我正在尝试做这个answer 所做的事情。由于HTTP GCP cloud function 的入口点接受请求AFAIK。我可以想办法让 Flask 像我提到的示例中那样解析 URL 参数。
【问题讨论】:
标签: google-cloud-platform google-cloud-functions
网址参数不是很清楚。如果说查询参数(url ? 后面的参数),直接取getting started example
def hello_world(request):
request_json = request.get_json()
# Here the query parameters
if request.args and 'message' in request.args:
return request.args.get('message')
# Here it's in the post body in JSON
elif request_json and 'message' in request_json:
return request_json['message']
else:
return f'Hello World!'
如果说路径参数,可以依赖view_args值
# Function code
def entrypoint(request):
return request.view_args, 200
# Test like that
> curl https://us-central1-<PROJECT ID>.cloudfunctions.net/<FUNCTION NAME>/test/to/path
> {"path":"test/to/path"}
但是,path 参数并没有为你拆分,需要你手动处理。
编辑 1
我找到了如何破解 Flask 并使用它的 URL 处理器。这是我的工作代码示例
# Function code
from flask import Flask
def entrypoint(request):
path = request.view_args['path']
f = Flask("internal")
f.add_url_rule("/test/<string:id>", "entrypoint_internal")
r = f.test_request_context(path=path)
r.push()
path_value = r.request.view_args
r.pop()
return path_value, 200
# Test like that
> curl https://us-central1-<PROJECT ID>.cloudfunctions.net/<FUNCTION NAME>/test/path
> {"id":"path"}
【讨论】: