2017-07-31 91 views
2

我使用PyDrive在Google Drive中创建文件,但我在实际的Google Doc类型项目中遇到了问题。PyDrive:创建一个Google Doc文件

我的代码是:

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

file.SetContentString("Hello World") 

file.Upload() 

如果我改变MIME类型,以text/plain这工作得很好,但因为是它给我的错误:

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

,如果我离开的MimeType它也能正常工作原样,但删除了对SetContentString的调用,所以看起来这两件事情并不一致。

什么是创建Google文档并设置内容的正确方法?

+0

附加:从这个[文件]根据(https://developers.google.com/drive/v3/reference/files/创建),如果未提供任何值,云端硬盘将尝试自动检测上传内容的适当值。除非上传新版本,否则无法更改该值。这里有一个相关的线程:https://stackoverflow.com/questions/43988753/googles-file-insert-v2-api-fails-to-recognise-mime-type-application-vnd-google – abielita

回答

2

Mime类型必须匹配上传的文件格式。您需要一种支持格式的文件,并且需要使用匹配的内容类型上传文件。因此,要么:

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

可以通过Google笔记本访问此文件。或者,

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

它可以使用Google文档打开。支持的格式列表和相应的MIME类型可以在here找到。

要转换的文件在运行到谷歌文档格式,使用方法:

file.Upload(param={'convert': True}) 
+0

这似乎是反直觉。为了使用Google Docs专有格式和Google Docs API,我必须上传不同的格式并进行转换...将其作为文本/纯文本格式,然后将转换命令添加到Upload工作,谢谢 – awestover89