Python部署的Cloud Function如何获取自身版本号
Python 语言 Cloud Function 访问自身版本号的实现方案
方案1:读取内置环境变量 (仅支持第二代 Cloud Function)
第二代 Google Cloud Function 运行时会自动注入K_REVISION环境变量,存储当前部署版本的唯一标识,无需额外配置即可直接读取:
import os def your_function_entry(request): # 第二个参数为本地测试时的默认值 current_version = os.environ.get("K_REVISION", "local_dev") return f"函数版本:{current_version}"
方案2:部署时手动注入版本标识 (支持一/二代 Cloud Function)
如果使用第一代 Cloud Function,没有内置版本环境变量,可以在部署命令中通过自定义环境变量传入版本号:
部署命令示例
gcloud functions deploy 你的函数名 \ --runtime python311 \ --trigger-http \ --set-env-vars FUNCTION_VERSION=v1.2.0
代码读取示例
import os def your_function_entry(request): current_version = os.environ.get("FUNCTION_VERSION", "local_dev") return current_version
方案3:调用官方 API 动态查询 (无部署前置要求)
如果不想在部署时手动指定版本,也可以在函数内部调用 Cloud Functions 官方 API 动态拉取版本信息:
- 先安装依赖包:
pip install google-cloud-functions - 给函数的运行时服务账号授予
Cloud Functions Viewer角色,保证API调用权限 - 代码示例:
import os from google.cloud import functions_v2 def your_function_entry(request): client = functions_v2.FunctionServiceClient() # 从内置环境变量获取当前函数的基础信息 project_id = os.environ.get("GCP_PROJECT") region = os.environ.get("FUNCTION_REGION") func_name = os.environ.get("FUNCTION_NAME") func_full_path = f"projects/{project_id}/locations/{region}/functions/{func_name}" func_info = client.get_function(name=func_full_path) # 兼容一二代版本字段 current_version = func_info.revision if hasattr(func_info, "revision") else func_info.version_id return f"当前版本:{current_version}"
内容的提问来源于stack exchange,提问作者TC Arlen
相关产品推荐
相关产品推荐

