使用googleapiclient请求库

时间:2018-05-17 23:20:07

标签: python oauth-2.0 google-api python-requests google-api-python-client

以下是使用httplib2库访问Google存储分区的代码

ManagedBy

有人能告诉我是否可以在这里使用Python Requests库发出http请求吗? 如果是,怎么样?

2 个答案:

答案 0 :(得分:2)

是的,您可以将HTTP标头Authorization: Bearer <access_token>与请求或任何您想要的库一起使用。

服务帐户

from google.oauth2 import service_account

credentials = service_account.Credentials.from_service_account_file(
    'services.json',
    scopes=['https://www.googleapis.com/auth/devstorage.read_only'],
)

# Copy access token
bearer_token = credentials.token

用户帐户凭据

import json

from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow

flow = InstalledAppFlow.from_client_secrets_file(
    'test.json',
    'https://www.googleapis.com/auth/devstorage.read_only'
)

# Construct cache path for oauth2 token
oauth2_cache_path = 'test-oauth2.json'

credentials = None

try:
    # Try to load existing oauth2 token
    with open(oauth2_cache_path, 'r') as f:
        credentials = Credentials(**json.load(f))
except (OSError, IOError) as e:
    pass

if not credentials or not credentials.valid:
    credentials = flow.run_console()

    with open(oauth2_cache_path, 'w+') as f:
        f.write(json.dumps({
            'token': credentials.token,
            'refresh_token': credentials.refresh_token,
            'token_uri': credentials.token_uri,
            'client_id': credentials.client_id,
            'client_secret': credentials.client_secret,
            'scopes': credentials.scopes,
        }))

# Copy access token
bearer_token = credentials.token

使用请求lib

import requests

# Send request
response = requests.get(
    'https://www.googleapis.com/storage/v1/<endpoint>?access_token=%s'
    % bearer_token)
# OR
response = requests.get(
    'https://www.googleapis.com/storage/v1/<endpoint>',
    headers={'Authorization': 'Bearer %s' % bearer_token})

使用googleapiclient lib

我建议你使用build()方法而不是直接请求,因为谷歌库在发送你的API调用之前会做一些检查(比如查看params,endpoint,auth和你使用的方法)。当检测到错误时,该库也会引发异常。

from googleapiclient.discovery import build

storage = build('storage', 'v1', credentials=credentials)
print(storage.objects().get(bucket='bucket', object='file_path').execute())

此处有更多信息:https://developers.google.com/identity/protocols/OAuth2WebServer#callinganapi(点击“HTTP / REST”标签)

答案 1 :(得分:0)

我建议使用已经实现了请求库的官方 Google Auth 库。有关更多信息,请参见this link

以下是要尝试的代码(假设您拥有具有所需权限的服务帐户):

from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession

service_account_file = 'service_account.json'
scopes = ['https://www.googleapis.com/auth/devstorage.full_control']
credentials = service_account.Credentials.from_service_account_file(
        service_account_file, scopes=scopes)
session = AuthorizedSession(credentials)
bucket_name = 'YOUR-BUCKET-NAME'
response = session.get(f'https://storage.googleapis.com/storage/v1/b/{bucket_name}')

print(response.json())