调用Google DLP Inspect API构建表格时遇ValueError问题求助
解决Google DLP Inspect API中
Value has no "stringValue" field错误 这个问题我之前也踩过坑,核心原因是Google DLP的Python客户端库和API Explorer使用的字段命名规则不一样:
- API Explorer调用的是JSON REST接口,字段名采用驼峰式的
stringValue - 而Python客户端基于Protobuf生成,字段名遵循PEP8的下划线命名法,对应的正确字段是
string_value
你只需要修改build_item_table方法里的字段名就能解决这个错误。
修正后的完整代码
def redact_text(text_list): dlp = google.cloud.dlp.DlpServiceClient() project = 'my-project' parent = dlp.project_path(project) items = build_item_table(text_list) info_types = [{'name': 'EMAIL_ADDRESS'}, {'name': 'PHONE_NUMBER'}] inspect_config = { 'min_likelihood': "LIKELIHOOD_UNSPECIFIED", 'include_quote': True, 'info_types': info_types } response = dlp.inspect_content(parent, inspect_config, items) return response def build_item_table(text_list): rows = [] for item in text_list: # 关键修改:将stringValue替换为string_value row = {"values": [{"string_value": item}]} rows.append(row) table = {"table": {"headers": [{"name": "something"}], "rows": rows}} return table
补充说明
Google Cloud的Python客户端库基本都是基于Protobuf自动生成的,所以字段名会统一从JSON的驼峰式转换为下划线式。比如:
- JSON里的
infoTypes→ Python里的info_types - JSON里的
includeQuote→ Python里的include_quote
以后遇到类似的字段不匹配问题,都可以优先检查这个命名规则差异,或者直接查看Python客户端DLP模块的源码消息定义来确认正确字段名。
内容的提问来源于stack exchange,提问作者CBredlow
相关产品推荐
相关产品推荐

