如何使用 google.oauth2 python 库?

问题描述 投票:0回答:3

我正在尝试对谷歌机器学习项目的安全预测端点进行简单的休息调用,但它找不到 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)。安装说是成功的。 蟒蛇版本:2.7.6 点子版本:1.5.4

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

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

安装模块有什么特殊的方法吗?如何验证模块是否已安装?有没有更简单的方法来对仅使用 Rest API 而不使用 python 的安全 ml 端点进行简单的 rest 调用?

python google-oauth google-api-python-client
3个回答
26
投票

google-oauth2 模块肯定存在,所以也许它从未安装过。

你有安装

google-auth
包吗?尝试执行

pip 安装 --upgrade google-auth

然后再次运行您的代码。


5
投票

安装 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


0
投票

我最近正在测试从 Python 调用 YouTube API v3(从 Rust 过渡),我最初为此苦苦挣扎,因为关于用法的 Google 文档不太清楚。

参考 Python 中的 快速入门部分 后,我得到了提示:

首先,我运行

pip install
来安装以下 Python 模块:

pip install \
    google-api-python-client~=2.85.0 \
    google-auth-oauthlib~=1.0.0 \
    google-auth-httplib2~=0.1.0

一旦安装了这些依赖项(最好是在虚拟环境中),剩下的就相当简单了。

设置一个 OAuth 应用程序并确保您有一个

client_secret.json
文件可以使用。

现在,您可以使用以下脚本进行测试——将

VIDEO_ID
替换为您个人频道或帐户下的YouTube视频ID(可见性:private)。

"""
Script to retrieve info on a (Private) video in an owned YT channel.

See:
    https://developers.google.com/docs/api/quickstart/python

"""
from pathlib import Path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build


# Enter a Video ("Private" visibility) in your YT Channel, for testing purposes
VIDEO_ID = 'REPLACE-ME'

# Parent Folder of this Python Script
SCRIPT_DIR = Path(__file__).parent

# The CLIENT_SECRET_FILE variable specifies the name of a file that contains
# the OAuth 2.0 information for this application, including its client_id and
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
# the Google API Console at
# https://console.cloud.google.com/.
# Please ensure that you have enabled the YouTube Data API for your project.
# For more information about using OAuth2 to access the YouTube Data API, see:
#   https://developers.google.com/youtube/v3/guides/authentication
# For more information about the client_secrets.json file format, see:
#   https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
CLIENT_SECRET_FILE = str(SCRIPT_DIR / 'client_secret.json')

# The file token.json stores the user's access and refresh tokens.
TOKEN_FILE = SCRIPT_DIR / 'token.json'

# OAuth 2.0 access scopes.
YOUTUBE_READ_ONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"
YOUTUBE_WRITE_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
SCOPES = [YOUTUBE_READ_ONLY_SCOPE, YOUTUBE_WRITE_SCOPE]

# API information
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"


def main():
    # API client
    youtube = get_authenticated_service()

    # Query for an owned video
    response = youtube.videos().list(
        part="id",
        id=VIDEO_ID,
    ).execute()

    # Print the result
    print(response)


def get_authenticated_service():
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if TOKEN_FILE.exists():
        creds = Credentials.from_authorized_user_file(str(TOKEN_FILE), SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                CLIENT_SECRET_FILE,
                scopes=SCOPES,
            )
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        TOKEN_FILE.write_text(creds.to_json())

    return build(
        YOUTUBE_API_SERVICE_NAME,
        YOUTUBE_API_VERSION,
        credentials=creds,
    )


if __name__ == '__main__':
    main()
© www.soinside.com 2019 - 2024. All rights reserved.