I have the following code that auto authenticates/authorizes my google drive access. I have copied the client_secrets.json file in my script's parent directory. The code opens a browser tab and waits for me to click "Accept". After I accept, the code continues to run, creates a folder (if not existing) and stores my file to it.
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
# Find the folder id
id = 0;
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
if file1['title'] == gpath:
id = file1['id']
# Make folder if it does not exist
if id == 0:
file1 = drive.CreateFile({'title': gpath, 'mimeType': 'application/vnd.google-apps.folder'})
file1.Upload()
# Fetch the folder id
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file1 in file_list:
if file1['title'] == gpath:
id = file1['id']
# Upload file to folder
file1 = drive.CreateFile({'title': fname, "parents": [{"kind": "drive#fileLink","id": id}]})
file1.SetContentFile(fname)
file1.Upload()
I want to run this script on a remote server and don't know if the server has a browser and/or if the script will run successfully on it. I would like to fully automate the process and not have the user click "Accept" on a browser and instead let the script handle everything without user intervention.
Also this is part of a very large script that runs for hours and will probably be programmed to run automatically every week or so. Hence any user dependence is highly undesirable.
I have tried Gerardo's method (from 2nd comment). I think I may have succeeded in auto authenticating my application. I created a service account and used SignedJwtAssertionCredentials to generate an authorized http object as follows:
from oauth2client.client import SignedJwtAssertionCredentials
from httplib2 import Http
client_email = 'xyz@developer.gserviceaccount.com'
with open("MyProject.p12") as f:
private_key = f.read()
credentials = SignedJwtAssertionCredentials(client_email, private_key, 'https://www.googleapis.com/auth/sqlservice.admin', sub='abc@example.com')
gauth = credentials.authorize(Http())
Not sure if my app is getting authorized. It does not throw any errors, so I think it should work. I still need to upload my files to a folder. How do I proceed?