Search code examples
pythongoogle-apps-scriptweb-applicationsgoogle-drive-api

How to upload to google drive with python without authentication?


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?


Solution

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

    Server side:

    function doPost(e){
      const FOLDER_ID = '###FOLDER_ID###';
      const name = e.parameter.name;
      saveFile(e.postData.contents,name,FOLDER_ID);
      return ContentService.createTextOutput('Success');
    }
    
    function saveFile(data,name,id) { 
        const blob = Utilities.newBlob(Utilities.base64DecodeWebSafe(data));
        DriveApp.getFolderById(id)
        .createFile(blob.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 or guesses the web app url can upload to your drive. The entropy of the url is the only security.

    References: