how to upload to google drive with python

邮差的信 提交于 2019-12-14 01:50:48

问题


I want upload file 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?


回答1:


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:

  • Webapp guide
  • Requests library



回答2:


Without letting Google know who you are by authenticating with the API key and connecting your Drive account, this is impossible.

You can follow the quickstart guide for Python authentication with the Drive REST API here. To upload files, you can use the DRIVE_SERVICE.files().create() method in Python to upload a file to you Drive once you have gone through the authentication. The Upload file documentation can be found here.

For security reasons you can not upload files using the Drive API without first authenticating your application with your account. With the authentication code provided in the Quickstart tutorial you can authenticate your application with the https://www.googleapis.com/auth/drive.file scope.



来源:https://stackoverflow.com/questions/56808846/how-to-upload-to-google-drive-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!