首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用google.oauth2 python库?

如何使用google.oauth2 python库?
EN

Stack Overflow用户
提问于 2018-05-19 03:56:48
回答 2查看 16.2K关注 0票数 10

我正在尝试对一个谷歌机器学习项目的安全预测端点进行一个简单的rest调用,但它找不到google.oauth2模块。这是我的代码:

代码语言:javascript
复制
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))

当我运行这个命令时,我得到了这个错误:

代码语言:javascript
复制
Traceback (most recent call last):
  File "wakeUpMLServer.py", line 30, in <module>
    from google.oauth2 import service_account
ImportError: No module named oauth2

我使用pip (此处的说明:https://developers.google.com/api-client-library/python/apis/oauth2/v1)安装了google-api-python-client库。安装程序显示安装成功。Python版本: 2.7.6 Pip版本: 1.5.4

如果有冲突,你应该知道我也在同一台服务器上处理protobuf文件,所以我也安装了protobufs库。当我执行pip list时,它显示了两个库:

代码语言:javascript
复制
google-api-python-client (1.6.7)
protobuf (3.1.0.post1)

有什么特殊的安装模块的方法吗?如何验证模块是否已安装?有没有更简单的方法可以只对一个只使用rest API而不使用python的受保护的ml端点进行简单的Rest调用?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-19 04:40:15

The google-oauth2 module definitely exists,所以可能它从来没有安装过。

您是否安装了google-auth包?尝试执行

pip install --升级google-auth

然后再次运行您的代码。

票数 14
EN

Stack Overflow用户

发布于 2021-11-26 20:19:04

安装Google API python包,

pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

然后,您可以使用oauth2凭据(确保service_account.json与您的脚本位于同一目录中)

代码语言:javascript
复制
import json
from googleapiclient.discovery import build
from google.oauth2.service_account import Credentials

service_account_info = json.load(open('service_account.json'))
credentials = Credentials.from_service_account_info(
            self.service_account_info, scopes=SCOPES)

drive_service = build('drive', 'v3', credentials=credentials)

有关更完整的教程,请访问https://developers.google.com/docs/api/quickstart/python

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50418449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档