Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyDrive: Create a Google Doc file

I am using PyDrive to create files in Google Drive, but I'm having trouble with the actual Google Doc type items.

My code is:

file = drive.CreateFile({'title': pagename, 
"parents":  [{"id": folder_id}], 
"mimeType": "application/vnd.google-apps.document"})

file.SetContentString("Hello World")

file.Upload()

This works fine if I change the mimetype to text/plain but as is it gives me the error:

raise ApiRequestError(error) pydrive.files.ApiRequestError: https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable&alt=json returned "Invalid mime type provided">

It also works fine if I leave the MimeType as is, but remove the call to SetContentString, so it appears those two things don't behave well together.

What is the proper way to create a Google Doc and set the content?

like image 906
awestover89 Avatar asked Jul 31 '17 04:07

awestover89


People also ask

How do I download files from PyDrive?

To download all the files in a particular directory get the id of the directory and use GetContentFile() to download all the files. Everytime you run the quickstart.py, you will be asked for the verification code. In order to automate the verification, you can add a settings. yaml file to your folder.

How do I use PyDrive?

PyDrive makes your life much easier by handling complex authentication steps for you. Go to APIs Console and make your own project. Search for 'Google Drive API', select the entry, and click 'Enable'. Select 'Credentials' from the left menu, click 'Create Credentials', select 'OAuth client ID'.


1 Answers

Mime type must match the uploaded file format. You need a file in one of supported formats and you need to upload it with matching content type. So, either:

file = drive.CreateFile({'title': 'TestFile.txt', 'mimeType': 'text/plan'})
file.SetContentString("Hello World")
file.Upload()

This file can be accessed via Google Notebook. Or,

file = drive.CreateFile({'title': 'TestFile.doc', 
                         'mimeType': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'})
file.SetContentFile("TestFile.docx")
file.Upload()

which can be opened with Google Docs. List of supported formats and corresponding mime types can be found here.

To convert file on the fly to Google Docs format, use:

file.Upload(param={'convert': True})
like image 147
Maciej Małycha Avatar answered Sep 28 '22 03:09

Maciej Małycha