Frage

I am creating a backup script for my GDrive folder. Every run I need to confirm to Google that the script can access GDrive. However, after the first run the verification code should be saved. In this post they mention a solution with a web server(Fulfilling Google Drive API OAuth2.0 Procedure w/o needing to find a verification code) - but I am looking for a solution for a simple backup script without a web server.

  • Is there a class which I can use instead of OAuth2WebServerFlow to retrieve correct credentials with an existing verification code? Is there a way to skip step1_get_authorize_url()? Or should I use oauth2 directly for this purpose?

My Code

    flow = OAuth2WebServerFlow(self.CLIENT_ID, self.CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI, offline=True)
    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    print
    code =  raw_input('Enter verification code: ').strip()
    credentials = flow.step2_exchange(code)
    http = httplib2.Http()
    http = credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
War es hilfreich?

Lösung

Is this a command line tool? If so, try the following which will persist the credentials after prompting you the first time:

import httplib2
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets
from oauth2client.tools import run
from apiclient.discovery import build

storage = Storage("saved_user_creds.dat")
credentials = storage.get()
if credentials is None or credentials.invalid:
  credentials = run(flow_from_clientsecrets("client_secrets2.json", scope=["https://www.googleapis.com/auth/drive"]), storage)
http = credentials.authorize(httplib2.Http())
service = build("drive", "v2", http)
print service.files().list().execute()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top