簡體   English   中英

如何使用 google.oauth2 python 庫?

[英]How do I use google.oauth2 python library?

我正在嘗試對谷歌機器學習項目的安全預測端點進行簡單的休息調用,但它找不到 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 庫(來自此處的說明: https : //developers.google.com/api-client-library/python/apis/oauth2/v1 )。 安裝說成功了。 Python 版本:2.7.6 Pip 版本:1.5.4

如果它有某種沖突,你應該知道我也在同一台服務器上進行 protobuf 文件處理,所以我也安裝了 protobufs 庫。 當我執行 pip list 時,它會顯示兩個庫:

google-api-python-client (1.6.7)
protobuf (3.1.0.post1)

我應該安裝模塊有什么特殊的方法嗎? 如何驗證模塊是否已安裝? 有沒有更簡單的方法可以對只使用 Rest API 而沒有 python 的安全 ml 端點進行簡單的 rest 調用?

google-oauth2模塊肯定存在 ,所以它可能從未安裝過。

你有安裝google-auth軟件包嗎? 嘗試執行

pip install --upgrade google-auth

然后再次運行您的代碼。

安裝 Google API python 包,

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

然后您可以使用 oauth2 憑證(確保service_account.json與您的腳本在同一目錄中)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM