问题
I have been successfully uploading files to a google-drive-folder with PyDrive. But, when it comes to uploading files to a folder in a google-drive-teamdrive-folder which is shared with me, the following code is not working.
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
location_to_save = "D:\images"
mImageLoc = location_to_save + "\\abcd.jpg"
#[...Code to fetch and save the file as abcd.jpg ...]
gfolder_id = "1H1gjBKcpiHJtnXKVxWQEC1CS8t4Gswjj" #This is a google drive folder id. I am replacing this with a teamdrive folder id, but that does not work
gfile_title = mImageLoc.split("\\")[-1] # returns abcd.jpg
http = gdrive.auth.Get_Http_Object()
f = gdrive.CreateFile({"parents": [{"kind": "drive#fileLink", "id": gfolder_id}],
'title': gfile_title})
f.SetContentFile(mImageLoc)
f.Upload(param={"http": http})
The error message I am recieving is: pydrive.files.ApiRequestError: <HttpError 404 when requesting https://www.googleapis.com/upload/drive/v2/files?alt=json&uploadType=resumable returned "File not found: 0AG-N4DqGC1nbUk9PVA">
'0AG-N4DqGC1nbUk9PVA' is the teamdrive's folder id here.
I have been searching for means to upload files to Teamdrives with PyDrive but in vain. I see in the pydrive's github pages that they added the teamdrives support approx 8 month ago. But I cannot find any documentation on how to use that. Can anyone suggest where I am being wrong please?
回答1:
For uploading, try making a file called "settings.yaml" and saving it in your working directory, as per the instructions here: https://pythonhosted.org/PyDrive/oauth.html
You will need the client id and client secret found in the client_secrets.json file which should also be in your directory after you authorised access to the Google API.
Test it out with the following code to make a text file in a folder in the team drive:
parent_folder_id = 'YYYY'
f = drive.CreateFile({
'title': 'test.txt',
'parents': [{
'kind': 'drive#fileLink',
'teamDriveId': team_drive_id,
'id': parent_folder_id
}]
})
f.SetContentString('Hello World')
f.Upload(param={'supportsTeamDrives': True})
# where XXXX and YYYY are the team drive and target folder ids found from the end of the URLS when you open them in your browser.
来源:https://stackoverflow.com/questions/53267728/upload-file-to-google-drive-teamdrive-folder-with-pydrive