How to use google API without web browser

I am writing a python script that tries to back up all required configuration files from my Linux VM to google drive cloud. I would like to do this automatically, without having to enter the confirmation code from the browser every time I run the script. Could you please advise me how to do this?

#!/usr/bin/python

import httplib2
import pprint
import credentials as cred
from apiclient.discovery import build
from apiclient.http import MediaFileUpload
from oauth2client.client import OAuth2WebServerFlow, FlowExchangeError

# Path to the file to upload
FILENAME = 'hello.py'

# Run through the OAuth flow and retrieve credentials from credentials.py


def api_upload(FILENAME):

    flow = OAuth2WebServerFlow(cred.credentials['CLIENT_ID'], cred.credentials['CLIENT_SECRET'],
                               cred.credentials['OAUTH_SCOPE'],
                               redirect_uri=cred.credentials['REDIRECT_URI'])

    authorize_url = flow.step1_get_authorize_url()
    print 'Go to the following link in your browser: ' + authorize_url
    code = raw_input('Enter verification code: ').strip()

    credentials = ''
    try:
        credentials = flow.step2_exchange(code)
    except FlowExchangeError:
        print "Your verification code is incorrect or something else is broken."
        exit(1)

    # Create an httplib2.Http object and authorize it with our credentials
    http = httplib2.Http()
    http = credentials.authorize(http)

    drive_service = build('drive', 'v2', http=http)

    # Insert a file
    try:
        media_body = MediaFileUpload(FILENAME, mimetype='text/plain',     resumable=True)
        body = {
            'title': "" + FILENAME,
            'description': 'A test document',
            'mimeType': 'text/plain'
        }
        upload_file = drive_service.files().insert(body=body, media_body=media_body).execute()
        pprint.pprint(upload_file)
    except IOError:
        print "No such file"
        exit(1)

# Function usage:
api_upload(FILENAME)

      

Here is my example function.

Another file stores the credentials for the request:

credentials = {"CLIENT_ID": 'blablabla',
               "CLIENT_SECRET": 'blablabla',
               "OAUTH_SCOPE": 'https://www.googleapis.com/auth/drive',
               "REDIRECT_URI": 'urn:ietf:wg:oauth:2.0:oob'}

      

+3


source to share


1 answer


Basically, you want to split this script into two separate scripts, one that receives the code and exchanges it for an access token, and one that uses an access token to access your Google Drive. I would split the above code into two chunks with the following changes.

In the first part, you can continue as you did above, but in your original request to get the code, set access_type to 'offline' and confirm_prompt to 'force' (see https://developers.google.com/identity/protocols / OAuth2WebServer ). If you do this, then during the exchange of the code, the returned token will contain not only an access_token, but also a refresh_token, which can be used to renew the access token indefinitely. So this first script should just save those tokens to a file and exit. If you can make this work, you only need to run this bit of code (with its manual intervention) once.



Then your second script can simply load the saved markers from the file whenever it should run and access its documents without intervention.

+1


source







All Articles