如何使用google.oauth2 Python库?解决模块导入失败及ML端点调用问题
解决Google OAuth2模块缺失及ML端点调用问题
问题描述
我正尝试为Google机器学习项目的安全预测端点发起一个简单的REST调用,但找不到google.oauth2模块。以下是我的代码:
import urllib2 from google.oauth2 import service_account # Constants ENDPOINT_URL = 'ml.googleapis.com/v1/projects/{project}/models/{model}:predict?access_token=' SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin'] SERVICE_ACCOUNT_FILE = 'service.json' credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) access_token=credentials.get_access_token() opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(ENDPOINT_URL) request.get_method = lambda: 'POST' result = opener.open(request).read() print(str(result))
运行代码时触发如下错误:
Traceback (most recent call last): File "wakeUpMLServer.py", line 30, in <module> from google.oauth2 import service_account ImportError: No module named oauth2
我已经通过pip安装了google-api-python-client库,安装过程提示成功。我的Python版本是2.7.6,Pip版本为1.5.4。另外服务器上还安装了protobuf库用于处理protobuf文件,执行pip list显示两个库都已存在:
google-api-python-client (1.6.7) protobuf (3.1.0.post1)
想请教:该模块是否有特殊安装方式?如何验证模块已安装?有没有更简单的方法,不用Python直接通过REST API调用安全ML端点?
解决方案
1. 修复google.oauth2模块缺失问题
你安装的google-api-python-client版本(1.6.7)比较老旧,而google.oauth2模块并不属于这个库,它是独立的google-auth库的一部分。针对Python 2.7,你需要安装适配版本的google-auth和配套的google-auth-httplib2:
pip install google-auth==1.35.0 google-auth-httplib2==0.1.0
注意:Python 2.7已经停止官方维护,建议尽快升级到Python 3.x版本,以获得更好的兼容性和安全保障。
2. 验证模块是否安装成功
有两种简单的验证方式:
- Python交互环境验证:打开Python终端,执行
from google.oauth2 import service_account,如果没有抛出错误,说明模块已经成功安装。 - pip命令验证:执行
pip show google-auth,输出内容会包含模块的安装路径和版本信息,确认路径位于你的Python 2.7的site-packages目录下即可。
3. 修正你的Python代码
除了模块问题,你的代码还有几处需要调整才能正常工作:
- 端点URL缺少
https://前缀,会导致请求失败 - 访问令牌需要通过
Authorization头传递,而不是拼在URL中 - 预测请求必须携带JSON格式的请求体(包含模型输入数据)
修正后的示例代码如下:
import urllib2 import json from google.oauth2 import service_account # 替换为你的实际项目和模型信息 PROJECT_ID = "your-project-id" MODEL_NAME = "your-model-name" ENDPOINT_URL = f'https://ml.googleapis.com/v1/projects/{PROJECT_ID}/models/{MODEL_NAME}:predict' # ML预测需要的正确权限,替换成你实际需要的 scope SCOPES = ['https://www.googleapis.com/auth/cloud-platform'] SERVICE_ACCOUNT_FILE = 'service.json' # 获取凭证和访问令牌 credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES) access_token = credentials.get_access_token().token # 构造模型输入数据,根据你的模型要求调整 request_body = json.dumps({ "instances": [ {"features": [1.0, 2.0, 3.0]} ] }) # 发起POST请求 opener = urllib2.build_opener(urllib2.HTTPHandler) request = urllib2.Request(ENDPOINT_URL, data=request_body) request.add_header('Authorization', f'Bearer {access_token}') request.add_header('Content-Type', 'application/json') try: result = opener.open(request).read() print(str(result)) except urllib2.HTTPError as e: print(f"请求失败:{e.code} - {e.read()}")
4. 无需Python直接调用REST API的方法
你可以使用curl命令直接发起请求,步骤如下:
- 获取访问令牌:先用服务账号密钥激活身份并获取令牌
gcloud auth activate-service-account --key-file=service.json gcloud auth print-access-token
- 发起预测请求:将上面获取到的令牌替换到
YOUR_ACCESS_TOKEN位置,同时替换项目和模型信息
curl -X POST \ -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "instances": [ {"features": [1.0, 2.0, 3.0]} ] }' \ https://ml.googleapis.com/v1/projects/YOUR_PROJECT/models/YOUR_MODEL:predict
或者你可以用一条命令完成,让curl自动获取令牌:
curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ -d '{ "instances": [ {"features": [1.0, 2.0, 3.0]} ] }' \ https://ml.googleapis.com/v1/projects/YOUR_PROJECT/models/YOUR_MODEL:predict
内容的提问来源于stack exchange,提问作者Alex Egli
相关产品推荐
相关产品推荐

