Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyDrive and Google Drive - automate verification process?

I'm trying to use PyDrive to upload files to Google Drive using a local Python script which I want to automate so it can run every day via a cron job. I've stored the client OAuth ID and secret for the Google Drive app in a settings.yaml file locally, which PyDrive picks up to use for authentication.

The problem I'm getting is that although this works some of the time, every so often it decides it needs me to provide a verification code (if I use CommandLineAuth), or it takes me to a browser to enter the Google account password (LocalWebserverAuth), so I can't automate the process properly.

Anybody know which settings I need to tweak - either in PyDrive or on the Google OAuth side - in order to set this up once and then trust it to run automatically without further user input in future?

Here's what the settings.yaml file looks like:

client_config_backend: settings
client_config:
  client_id: MY_CLIENT_ID
  client_secret: MY_CLIENT_SECRET

save_credentials: True
save_credentials_backend: file
save_credentials_file: credentials.json

get_refresh_token: False

oauth_scope:
  - https://www.googleapis.com/auth/drive.file
like image 790
Chris Webster Avatar asked Mar 21 '14 09:03

Chris Webster


1 Answers

You can (should) create a service account - with an id and private key from the google API console - this won't require re verification but you'll need to keep the private key private.

Create a credential object based on the google python example and assign it to the PyDrive GoogleAuth() object:

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

# from google API console - convert private key to base64 or load from file
id = "[email protected]"
key = base64.b64decode(...)

credentials = SignedJwtAssertionCredentials(id, key, scope='https://www.googleapis.com/auth/drive')
credentials.authorize(httplib2.Http())

gauth = GoogleAuth()
gauth.credentials = credentials

drive = GoogleDrive(gauth)

EDIT (Sep 2016): For the latest integrated google-api-python-client (1.5.3) you would use the following code, with id and key the same as before:

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

credentials = ServiceAccountCredentials.from_p12_keyfile_buffer(id, StringIO.StringIO(key), scopes='https://www.googleapis.com/auth/drive')
http = credentials.authorize(httplib2.Http())
drive = discovery.build("drive", "v2", http=http)
like image 95
Andrew Smallbone Avatar answered Nov 07 '22 07:11

Andrew Smallbone