在python中对Google api执行oauth2 headless

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

Google的youtube Analytics API仅基于Oauth2。我正在使用以下测试脚本来查看是否可以访问:

import os
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ['https://www.googleapis.com/auth/yt-analytics.readonly']

API_SERVICE_NAME = 'youtubeAnalytics'
API_VERSION = 'v2'
CLIENT_SECRETS_FILE = 'client_secret.json'
def get_service():
  flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
  credentials = flow.run_console()
  return build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

def execute_api_request(client_library_function, **kwargs):
  response = client_library_function(
    **kwargs
  ).execute()

  print(response)

if __name__ == '__main__':
  # Disable OAuthlib's HTTPs verification when running locally.
  # *DO NOT* leave this option enabled when running in production.
  os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'

  youtubeAnalytics = get_service()
  execute_api_request(
      youtubeAnalytics.reports().query,
      ids='channel==MINE',
      startDate='2017-01-01',
      endDate='2017-12-31',
      metrics='estimatedMinutesWatched,views,likes,subscribersGained',
      dimensions='day',
      sort='day'
  )

我的问题是该脚本要求我打开浏览器,设置链接,登录,然后获得令牌电缆。

有没有办法在“无头”模式下执行此操作?我需要提取这些API以进行机器到机器的传输。

谢谢!

python google-api google-api-client google-api-python-client
1个回答
0
投票

执行一次,然后将credentials = flow.run_console()返回的凭据对象保存到数据库或文件中。它包含一个“刷新令牌”,可以在后续的api调用中使用它,这意味着您可以跳过flow.run_console步骤,而只需在credentials调用中使用保存的build(API_SERVICE_NAME, API_VERSION, credentials = credentials)

此处有关于此文档的注释:

https://developers.google.com/youtube/reporting/guides/authorization/installed-apps#exchange-authorization-code

© www.soinside.com 2019 - 2024. All rights reserved.