Using Pydrive for automatic uploading

903 Views Asked by At

I am using Pydrive module for uploading files to my google drive. The code which I am using:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()           
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth) 

file1 = drive.CreateFile({'title': 'hello.txt'})
file1.SetContentString('Hello world project')
file1.Upload()

When I run this code, browser opens and I need to click on the google account for sign in. This process repeats everytime I run the code. Is there a way where on running the code, the file uploads automatically? like providing google email account and password in the code.

1

There are 1 best solutions below

0
Meet Gondaliya On

Originally answered in this Question

To automatically Upload Files to Google Drive via PyDrive module use this code template

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()

# ---Try to load saved client credentials ---#

gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # Authenticate if they're not there
    gauth.LocalWebserverAuth()
elif gauth.access_token_expired:
    # Refresh them if expired
    gauth.Refresh()
else:
    # Initialize the saved creds
    gauth.Authorize()
# Save the current credentials to a file
gauth.SaveCredentialsFile("mycreds.txt")

# ------------------------------------------ # 

gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth) 

file1 = drive.CreateFile()
file1.SetContentFile('shoe.png')
file1.Upload()