6

(为了清楚起见,这篇文章涉及到谷歌Documents List APIGoogle Drive API之间的Google App Engine与Python的区别)编辑谷歌文档与驱动API

随着[现已弃用]文档列表API,我能够编辑谷歌文档通过导出为HTML,修改HTML然后重新上传,无论是作为新文档还是作为原始修改。这对于从模板生成PDF文档等很有用。我一直在尝试使用新的Drive API(V2)复制此功能,但似乎无法完成。

想出了这个...

http = # authenticated http client 
drive_service = build('drive', 'v2', http=http) 

# get the file ... 
file = drive_service.files().get(fileId=FILE_ID).execute() 

# download the html ... 
url = file['exportLinks']['text/html'] 
response, content = http.request(url) 

# edit html 
html = content.replace('foo', 'bar') 

# create new file with modified html ... 
body = {'title':'Modified Doc', 
     'description':'Some description', 
     'mimeType':'text/html'} 
media_body = MediaIoBaseUpload(StringIO.StringIO(html), 'text/html', resumable=False) 
drive_service.files().insert(body=body, media_body=media_body) 

上面的代码上传一个HTML文件作为一个文件到谷歌驱动器,而不是HTML呈现到谷歌文档。公平,这是有道理的。但是,如何将它呈现为Google文档,就像我能够使用文档列表API一样?

另一件事 - 如果我设置resumable = True它会在App Engine上引发以下错误 - '_StreamSlice'没有len()。无法弄清楚如何获得可恢复=真正的工作?

还有最后一件事 - sample code in the docs使用MediaInMemoryUpload对象,但if you look at the source现在不赞成使用MediaIoBaseUpload。示例代码是否应该更新?

回答

7

我怀疑问题是转换的默认值已从true更改为false。您必须在上传中明确设置convert = true。请参阅https://developers.google.com/drive/v2/reference/files/insert

+0

完全正确。不能相信我错过了这一点。谢谢! –

+0

但是你在哪里设置convert = true?这些例子都没有描述参数设置的位置。修补service.files()。insert()。execute.uri会抛出错误,并且文件和插入都不会采用正确的参数。 ruby版本的apiclient采用.execute()参数参数。 – Sethish

+2

作为插入方法的参数传递。像这样drive_service.files()。insert(body = body,media_body = media_body,convert = True).execute()。它记录在这里https://developers.google.com/drive/v2/reference/files/insert –