Exemple de compte de service Python de l'API Google Drive

Oct 28 2020

Est-il possible de s'authentifier auprès de l'API Google Drive à l'aide d'un compte de service Google plutôt que d'un flux OAuth?

Les exemples Python pour Google Drive utilisent OAuth - Démarrage rapide de Google Drive Python

Cependant, je ne trouve aucun exemple de compte de service.

La plupart des autres utilisent des API Google I (Traduire, Nuage Vision) ne utiliser le service compte cependant, je voudrais désapprouver mon code Google Drive OAuth pour la cohérence.

Réponses

2 DaImTo Oct 28 2020 at 17:19

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.