Google Colab中curl转Python后Google认证失败的解决求助
解决Google Healthcare NLP服务Python调用的认证问题
问题背景
在Google Colab中,原本可用的curl命令能正常调用Google Healthcare NLP服务,但通过工具转换为Python代码后,始终卡在认证环节,报错ValueError: Invalid header value b'Bearer <<access token>>'。尝试手动设置认证凭证后仍无法解决。
核心错误原因
- Token末尾带换行符:通过
subprocess获取的access token会包含末尾的换行符,导致Authorization头格式不符合要求。 - JSON字符串拼接错误:手动拼接JSON时容易出现转义错误,同时未正确处理文本中的特殊字符,进一步引发请求格式问题。
修正后的Python实现
方案1:修复requests版本代码
直接修正原代码中的token处理和JSON拼接问题:
import subprocess import requests import json # 读取文件内容,避免用subprocess调用cat with open('/content/drive/MyDrive/myfile.txt', 'r') as f: document_content = f.read() # 获取access token并去除末尾换行符 token_process = subprocess.run( 'gcloud auth application-default print-access-token', shell=True, capture_output=True, text=True ) access_token = token_process.stdout.strip() # 关键:去除换行符 headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json; charset=utf-8', } # 用字典+json.dumps自动处理转义,避免手动拼接出错 payload = { "nlpService": "projects/PROJECTNAME/locations/us-central1/services/nlp", "documentContent": document_content } response = requests.post( 'https://healthcare.googleapis.com/v1/projects/PROJECTNAME/locations/us-central1/services/nlp:analyzeEntities', headers=headers, json=payload # 使用requests的json参数自动序列化,更可靠 ) # 验证响应 print("响应状态码:", response.status_code) if response.ok: print("响应结果:", response.json()) else: print("错误信息:", response.text)
方案2:使用Google官方客户端库(推荐)
官方库会自动处理认证、请求序列化等细节,避免手动处理的各种问题:
from google.cloud import healthcare_v1 # 确保Colab已完成认证(首次运行需执行) # !gcloud auth application-default login # 初始化NLP服务客户端 client = healthcare_v1.NlpServiceClient() # 配置服务名称和文档内容 nlp_service_name = "projects/PROJECTNAME/locations/us-central1/services/nlp" # 读取目标文本文件 with open('/content/drive/MyDrive/myfile.txt', 'r') as f: document_text = f.read() # 构建请求对象 document = healthcare_v1.Document( content=document_text, type_=healthcare_v1.Document.Type.PLAIN_TEXT ) request = healthcare_v1.AnalyzeEntitiesRequest( name=nlp_service_name, document=document ) # 发送请求并处理结果 response = client.analyze_entities(request=request) # 输出识别到的实体 for entity in response.entities: print(f"实体类型: {entity.type_.name}") print(f"实体文本: {entity.text.content}") print(f"置信度: {entity.confidence}\n")
额外说明
- 若使用官方库,需先安装依赖:
!pip install google-cloud-healthcare - 替换代码中的
PROJECTNAME为你的Google Cloud项目ID - 确保Colab已挂载Google Drive,且文件路径正确
内容的提问来源于stack exchange,提问作者Sunny League
相关产品推荐
相关产品推荐

