How to upload to google drive with python without authentication?

Viewed 1431

I want to upload files to Google Drive with Google Script and Python.

I don't want to do this with API because it's with JSON file and requesting a password to google account.

I want to send from the Python file without a JSON file and without requesting a google account.

I want to create a script in google script that will upload the file to the site.

I found how to do it with html:

function saveFile(data,name,folderName) { 
   var contentType = data.substring(5,data.indexOf(';'));

   var file = Utilities.newBlob(
     Utilities.base64Decode(data.substr(data.indexOf('base64,')+7)), 
     contentType, 
     name
   ); //does the uploading of the files
   DriveApp.getFolderById(childFolderIdA).createFile(file);
}

But I did not find how to do it with python.

How do I send file with file to this code?

2 Answers

You can do this by publishing a web app to run as "Me"(you) with access: "Anyone, even anonymous".

Server side:

function doPost(e){
  const FOLDER_ID = '###FOLDER_ID###';
  var name = e.parameter.name;
  saveFile(e.postData.contents,name,FOLDER_ID);
  return 'Success';
}

function saveFile(data,name,id) { 
    data = Utilities.newBlob(Utilities.base64DecodeWebSafe(data));
    DriveApp.getFolderById(id)
    .createFile(data.setName(name))
}

Client side:

import requests, base64
url = '###WEB_APP_PUBLISHED_URL###'
name = '###FILENAME###'
requests.post(url+'?name='+name,data=base64.urlsafe_b64encode(open('##UPLOAD FILE PATH##','rb').read()))

Note:

  • Anyone who knows the web app url can upload to your drive

References:

gauth = GoogleAuth()           
drive = GoogleDrive(gauth)
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()           
drive = GoogleDrive(gauth)

upload_file_list = ['1.jpg', '2.jpg']
for upload_file in upload_file_list:
    gfile = drive.CreateFile({'parents': [{'id': '1pzschX3uMbxU0lB5WZ6IlEEeAUE8MZ-t'}]})
    # Read file and set it as the content of this instance.
    gfile.SetContentFile(upload_file)
    gfile.Upload() # Upload the file.
Related