使用Drive API编辑Google文档

7
(为了更清晰,本文涉及谷歌文档列表APIGoogle Drive APIGoogle App Engine上的差异)
使用[现已停用的]文档列表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文件上传为文件到Google Drive,而不是将HTML渲染为Google文档。这是有道理的。但是,我该如何让它呈现为Google文档,就像我使用Documents List API时所能做的那样?
另外一件事-如果我设置resumable=True,它会在App Engine上抛出以下错误-'_StreamSlice'没有len()。无法弄清楚如何使resumable=True工作?
最后一件事-文档中的示例代码使用MediaInMemoryUpload对象,然而如果您查看源代码,它现在已经被弃用,而推荐使用MediaIoBaseUpload。示例代码应该更新吗?!
1个回答

7

但是你在哪里设置convert=true呢?没有一个例子描述参数的设置位置。修补service.files().insert().execute.uri会抛出错误,而且files和insert似乎都没有使用正确的参数。apiclient的ruby版本需要在.execute()中传递一个parameters参数。 - Sethish
2
将其作为参数传递给insert方法。像这样drive_service.files().insert(body=body, media_body=media_body, convert=True).execute()。文档在此处https://developers.google.com/drive/v2/reference/files/insert。 - Gwyn Howell
没关系,我自己回答了我的问题。你可以使用类似这样的代码: service.files().insert(body=resource, media_body=media, convert=True).execute() - Sethish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接