библиотека запросов с googleapiclient - PullRequest
0 голосов
/ 18 мая 2018

Ниже приведен код для доступа к корзине хранения Google с использованием библиотеки 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())

Может кто-нибудь сказать мне, могу ли я сделать запрос http с помощью библиотеки запросов Python здесь?Если да, то как?

1 Ответ

0 голосов
/ 18 мая 2018

Да, вы можете использовать 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 (), а не запросы напрямую, потому что библиотека Google выполняет некоторые проверки перед отправкой вызова 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»)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...