如何使用python上传到Google驱动器 [英] how to upload to google drive with python
问题描述
我想使用Google脚本和python将文件上传到Google驱动器.
I want upload file to google drive with google script and python.
我不想使用API进行此操作,因为它与json文件一起使用,并要求输入Google帐户的密码.
I don't want to do this with API because it's with json file and requesting a password to google account.
我想从Python文件发送不带json文件且不请求Google帐户的邮件.
I want to send from the Python file without a json file and without requesting a google account.
我想在google脚本中创建一个脚本,该脚本会将文件上传到网站.
I want to create a script in google script that will upload the file to the site.
我发现了如何使用html:
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);
}
但是我没有找到如何用python做到这一点.
But I did not find how to do it with python.
如何将文件和文件一起发送到此代码?
How do I send file with file to this code?
推荐答案
您可以通过发布一个Web应用程序来执行此操作,该应用程序以"Me"(您)的身份运行,访问权限为:任何人,甚至是匿名的".
You can do this by publishing a web app to run as "Me"(you) with access: "Anyone, even anonymous".
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))
}
客户端:
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()))