使用 googleapiclient 请求库

Sam*_*ain 2 python google-api oauth-2.0 python-requests google-api-python-client

以下是使用 httplib2 库访问谷歌存储桶的代码

import json
from httplib2 import Http
from oauth2client.client import SignedJwtAssertionCredentials
from googleapiclient.discovery import build
from pprint import pprint
client_email = 'my.iam.gserviceaccount.com'

json_file = 'services.json'


cloud_storage_bucket = 'my_bucket'

files = 'reviews/reviews_myapp_201603.csv'
private_key = json.loads(open(json_file).read())['private_key']

credentials = SignedJwtAssertionCredentials(client_email, 
private_key,'https://www.googleapis.com/auth/devstorage.read_only')
storage = build('storage', 'v1', http=credentials.authorize(Http()))
pprint(storage.objects().get(bucket=cloud_storage_bucket, object=files).execute())
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我是否可以使用 Python Requests 库发出 http 请求吗?如果是,如何?

Cal*_*mah 7

是的,您可以将 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
Run Code Online (Sandbox Code Playgroud)

用户帐户凭据

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
Run Code Online (Sandbox Code Playgroud)

使用请求库

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})
Run Code Online (Sandbox Code Playgroud)

使用 googleapiclient 库

我建议你使用 build() 方法而不是直接请求,因为谷歌库在发送你的 API 调用之前会做一些检查(比如检查参数、端点、身份验证和你使用的方法)。当检测到错误时,这个库也会引发异常。

from googleapiclient.discovery import build

storage = build('storage', 'v1', credentials=credentials)
print(storage.objects().get(bucket='bucket', object='file_path').execute())
Run Code Online (Sandbox Code Playgroud)

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