如何使用Google Cloud Functions官方Python客户端获取指定项目云函数列表
前置准备
- 首先安装官方推荐的依赖库:
pip install google-cloud-functions - 提前完成GCP身份鉴权配置:可通过设置环境变量
GOOGLE_APPLICATION_CREDENTIALS指向你的服务账号JSON密钥文件,若代码运行在已绑定服务账号的GCP环境(如Cloud Shell、GCE、GKE等)中可省略该步骤
同步客户端实现(CloudFunctionsServiceClient)
适合普通同步业务场景,直接调用即可返回指定项目下的所有云函数:
from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceClient def list_gcp_functions(project_id: str, location: str = "-") -> list: """ 获取指定GCP项目下的云函数列表 :param project_id: GCP项目ID :param location: 区域,传入"-"代表查询所有区域的函数 """ client = CloudFunctionsServiceClient() parent = f"projects/{project_id}/locations/{location}" functions = [] # 处理分页返回结果 for page in client.list_functions(parent=parent).pages: functions.extend(page.functions) return functions # 调用示例 if __name__ == "__main__": project_id = "替换为你的GCP项目ID" all_functions = list_gcp_functions(project_id) for func in all_functions: print(f"函数名称:{func.name},运行时:{func.runtime},触发方式:{'HTTPS触发' if func.https_trigger is not None else '其他触发'}")
异步客户端实现(CloudFunctionsServiceAsyncClient)
适合异步IO业务场景,调用逻辑和同步端基本一致:
import asyncio from google.cloud.functions_v1.services.cloud_functions_service import CloudFunctionsServiceAsyncClient async def list_gcp_functions_async(project_id: str, location: str = "-") -> list: client = CloudFunctionsServiceAsyncClient() parent = f"projects/{project_id}/locations/{location}" functions = [] async for page in client.list_functions(parent=parent).pages: functions.extend(page.functions) return functions # 调用示例 if __name__ == "__main__": project_id = "替换为你的GCP项目ID" all_functions = asyncio.run(list_gcp_functions_async(project_id)) for func in all_functions: print(f"函数名称:{func.name},运行时:{func.runtime}")
补充说明
- 上述示例使用的是v1版本接口,默认返回1代云函数,如果需要获取2代云函数,可将导入路径替换为
google.cloud.functions_v2.services.cloud_functions_service.CloudFunctionsServiceClient,调用逻辑完全不变 - 返回的函数实例包含全量配置字段,可按需提取状态、内存配置、触发事件、入口函数等信息
- 若仅需要查询单个区域的函数,将location参数替换为对应区域ID(如
us-central1)即可
内容的提问来源于stack exchange,提问作者jamiet
相关产品推荐
相关产品推荐

