Google DLP报错:'Resource'对象无'content'属性,测试脚本失效
解决Google DLP报错:'Resource' object has no attribute 'content'
这个错误是因为你的代码使用了过时的Google DLP API调用方式,或者客户端构建逻辑不正确导致的。我来帮你一步步排查修复:
核心原因
你调用的service.content()方法在当前版本的Google Cloud DLP Python客户端中已经不存在了——Google更新了DLP客户端的API结构,老的资源调用方式被替换成了更清晰的方法调用逻辑。
修复步骤
1. 确保依赖库是最新版本
首先升级google-cloud-dlp到最新版,避免版本兼容问题:
pip install --upgrade google-cloud-dlp
2. 重构客户端构建方法
原来的build_client()可能使用了过时的googleapiclient.discovery.build方式,换成官方推荐的客户端初始化方式:
from google.cloud import dlp_v2 def build_client(): # 这是当前版本DLP客户端的标准初始化方式 return dlp_v2.DlpServiceClient()
3. 修改redact_text函数的API调用
新的客户端使用redact_content方法来处理文本脱敏,同时请求参数结构有几个关键变化:
def redact_text(text_list, project_id): dlp_client = build_client() # 注意:内容类型的键从`type`改为`type_`(避开Python关键字) items = [] for text in text_list: items.append({"type_": "TEXT_PLAIN", "value": text}) # 替换配置的结构基本不变,但要确保redacts字典是正确定义的 replace_configs = [ {"replace_with": redacts[info], "info_type": {"name": info}} for info in redacts.keys() ] inspect_config = { "min_likelihood": "LIKELIHOOD_UNSPECIFIED", "max_findings": 0, "include_quote": False } # 必须指定项目作为parent,这是当前API的强制要求 parent = f"projects/{project_id}" request = { "parent": parent, "items": items, "inspect_config": inspect_config, "replace_configs": replace_configs } # 调用新的redact_content方法 response = dlp_client.redact_content(request=request) # 提取脱敏后的文本结果 return [item.value for item in response.items]
4. 额外检查项
- 确认你的
redacts字典是有效的,比如:redacts = { "EMAIL_ADDRESS": "[REDACTED_EMAIL]", "PHONE_NUMBER": "[REDACTED_PHONE]" # 按需添加其他需要脱敏的信息类型 } - 确保你的GCP认证配置正确(比如设置了
GOOGLE_APPLICATION_CREDENTIALS环境变量指向服务账号密钥文件) - 确认你的GCP项目已经启用了DLP API
内容的提问来源于stack exchange,提问作者CBredlow
相关产品推荐
相关产品推荐

