使用Python调用Google Cloud Functions API更新云函数标签时updateMask格式报错
报错核心原因
- 很多网上的Google API Python示例存在误导,把
updateMask写成列表格式,实际Cloud Functions v1接口的这个参数根本不接受列表入参,只认符合protobuf字段掩码规范的逗号分隔字符串 - 你代码里传的
updateMask = ['labels']列表格式,会被客户端序列化成带方括号的非法字符串,直接触发后端格式校验失败 - 另外有个容易踩的语义坑:patch接口传入的labels对象是全量覆盖逻辑,不是增量追加,直接传新的labels字典会把函数上原有的所有标签清空
具体修正步骤
- 把updateMask从列表改成纯字符串,单字段更新直接传
'labels'即可 - 后续如果需要同时更新多个字段,直接用英文逗号把所有要更新的字段名拼起来,比如
'labels,description,runtime',不要用列表包裹 - 调用patch之前先把get接口拿到的原有标签和新增标签做字典合并,避免误清空已有标签
修正后的代码片段
class MemoryCache(Cache): _CACHE = {} def get(self, url): return MemoryCache._CACHE.get(url) def set(self, url, content): MemoryCache._CACHE[url] = content scopes = ['https://www.googleapis.com/auth/cloud-platform'] credentials, project_id = google.auth.default(scopes) service = build('cloudfunctions', 'v1', credentials=credentials, cache=MemoryCache()) name = 'projects/my-project/locations/us-central1/functions/function-1' # 拉取现有函数配置,保留原有标签 existing_func = service.projects().locations().functions().get(name=name, x__xgafv=None).execute() existing_labels = existing_func.get('labels', {}) # 合并原有标签和新增的测试标签 final_labels = {**existing_labels, 'type': 'testing'} # 关键修正:updateMask改为字符串格式,不要传列表 updateMask = 'labels' body = {'labels': final_labels} result = service.projects().locations().functions().patch( name=name, updateMask=updateMask, body=body, x__xgafv=None ).execute()
注意点:updateMask里的字段名必须和接口返回的字段名完全一致,不能大小写错误,否则也会触发校验失败。
内容的提问来源于stack exchange,提问作者Aim_headshot
相关产品推荐
相关产品推荐

