【问题标题】:requests library with googleapiclient使用 googleapiclient 请求库
【发布时间】:2018-10-28 07:55:58
【问题描述】:

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

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())

谁能告诉我是否可以在这里使用 Python 请求库发出 http 请求? 如果是,怎么做?

【问题讨论】:

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


    【解决方案1】:

    是的,您可以将 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
    

    使用请求库

    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 库

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

    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”标签)

    【讨论】:

    • 您能否提供示例代码,因为我无法制定标题。谢谢你:)
    • @SamyakJain 完成 :)
    • 你好@Calumah,我使用了你的技术但是我仍然无法生成不记名令牌。是否有另一种生成令牌的方法?
    • @SamyakJain 我用更多信息更新了我的答案并将属性名称修复为`credentials.token`
    • 您好@Calumah,非常感谢您提供的信息。你也能告诉我为什么你认为构建对象比请求库更好吗?我的意思是我了解谷歌使用构建功能优化了所有内容,但还有其他原因吗?
    【解决方案2】:

    我建议使用已经实现 Requests 库的官方 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())
    

    【讨论】:

      猜你喜欢
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多