GCP:从Cloud Function调用另一个Cloud Function并异步返回启动结果
异步调用Cloud Function(仅确认启动成功,无需等待执行完成)
你当前的代码是同步调用Cloud Function,因此会一直等待目标函数执行完毕才收到响应。要实现仅确认启动成功就返回,有两种可靠的处理方式:
方式一:将目标Cloud Function配置为异步执行模式
这是GCP官方推荐的方案,部署目标函数时指定异步执行模式:
gcloud functions deploy test_function \ --runtime python311 \ --trigger-http \ --execution-mode=async \ --region europe-west1 \ --project YOUR_PROJECT_ID
配置完成后,调用该函数时GCP会立即返回202 Accepted响应,目标函数转至后台异步执行,调用方无需等待执行完成。
你的现有代码只需小幅调整即可适配(注意requests.post的json参数无需提前dumps,直接传入字典即可):
import json import requests import google.auth.transport.requests import google.oauth2.id_token def your_function(PROJECT_ID, file_info): url = f"https://europe-west1-{PROJECT_ID}.cloudfunctions.net/test_function" auth_req = google.auth.transport.requests.Request() id_token = google.oauth2.id_token.fetch_id_token(auth_req, url) auth_header = {"Authorization": f"Bearer {id_token}"} # 直接传入字典,requests会自动处理序列化 response = requests.post(url, json=file_info, headers=auth_header) # 检查是否成功启动异步执行 if response.status_code == 202: print("目标函数已成功启动执行") else: print(f"启动失败,响应码:{response.status_code},响应内容:{response.text}") return "File load triggered"
方式二:调用方使用非阻塞请求(仅作临时方案,可靠性低)
如果无法修改目标函数的部署配置,可以通过非阻塞请求实现发送后立即断开连接,但这种方式存在请求未被目标函数正确接收的风险,不适合生产环境:
import requests import google.auth.transport.requests import google.oauth2.id_token def your_function(PROJECT_ID, file_info): url = f"https://europe-west1-{PROJECT_ID}.cloudfunctions.net/test_function" auth_req = google.auth.transport.requests.Request() id_token = google.oauth2.id_token.fetch_id_token(auth_req, url) auth_header = {"Authorization": f"Bearer {id_token}"} try: # 开启stream模式,发送请求后立即关闭连接 response = requests.post(url, json=file_info, headers=auth_header, stream=True) # 仅确认请求已发送,不等待完整响应 response.close() print("请求已发送,目标函数启动中") except Exception as e: print(f"发送请求失败:{str(e)}") return "File load triggered"
关键提示
- 方式一的异步执行模式由GCP托管调度,能保证请求被可靠处理,是生产环境的首选方案。
- 方式二仅适合临时场景,可能出现请求丢失、目标函数未触发的情况。
内容的提问来源于stack exchange,提问作者Robertas Kirka
相关产品推荐
相关产品推荐

