Google Drive API Python Service Account Example

那年仲夏 提交于 2021-01-28 07:37:07

问题


Is it possible to authenticate against the Google Drive API using a Google Service Account, rather than an OAuth flow ?

The Python examples for Google Drive use OAuth - Google drive Python Quick start

However I can't find any Service Account examples.

The majority of the other Google APIs I use (Translate, Cloud Vision) do use Service Account however, so I'd like to deprecate my Google Drive OAuth code for consistency.


回答1:


The best service account python example that i know of is the one for Google analytics

It should be something like this.

from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials


SCOPES = ['https://www.googleapis.com/auth/drive.readonly']
KEY_FILE_LOCATION = '<REPLACE_WITH_JSON_FILE>'
VIEW_ID = '<REPLACE_WITH_VIEW_ID>'


def initialize_drive():
  """Initializes an service object.

  Returns:
    An authorized service object.
  """
  creds = ServiceAccountCredentials.from_json_keyfile_name(
      KEY_FILE_LOCATION, SCOPES)

  # Build the service object.
  service = build('drive', 'v3', credentials=creds)

  return service

Once you have the drive service you should be able to use the rest of the code you have from the other tutorial. Its just the auth method that is diffrent.

Just remember to create service account credentials and not Oauth credentials.



来源:https://stackoverflow.com/questions/64570647/google-drive-api-python-service-account-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!