Forums

Pythonanywhere with PyDrive and Google Drive

I have verified that the following code works on my local PC:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
path_to_your_file = 'file'

#1st authentification
gauth = GoogleAuth()
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.
drive = GoogleDrive(gauth)

file1 = drive.CreateFile()
file1.SetContentFile(path_to_your_file)
file1.Upload()

I have followed the Quickstart example from Pydrive that included creating a project, oauth-credentials and saving the client_secrets.json

With pythonanywhere, a browserprompt opens in the bash console: python anywhere user prompt

Has anyone recently used Pythonanywhere and PyDrive/GDrive file upload successfully? My App is unverified.

Maybe have a look at this bit of the docs and check if you'd be able to automate the authentication process without starting the local web server and using the client_secrets file generated on your local machine.

Also -- it's an old SO post, but maybe would be helpful in this context: https://stackoverflow.com/a/24542604/9536161.

Thanks, I got it working with automatic login:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
path_to_your_file = 'ffdb_daily_backup.sql'

gauth = GoogleAuth()
# Try to load saved client credentials
gauth.LoadCredentialsFile("mycreds.txt")
if gauth.credentials is None:
    # Authenticate if they're not there
    # This is what solved the issues:
    gauth.GetFlow()
    gauth.flow.params.update({'access_type': 'offline'})
    gauth.flow.params.update({'approval_prompt': 'force'})
    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")
drive = GoogleDrive(gauth)

file1 = drive.CreateFile()
file1.SetContentFile(path_to_your_file)
file1.Upload()

Glad to hear that you made it work!