使用驱动器API编辑Google文档

Gwy*_*ell 7 python google-app-engine google-drive-api google-api-python-client

(为清楚起见,这篇文章与使用Python的Google App Engine上的Google Documents List APIGoogle Drive API之间的差异有关)

使用[现已弃用的]文档列表API,我能够通过导出为HTML,修改HTML然后重新上载来编辑Google文档,作为新文档或作为原始文档的修改.这对于从模板生成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)
Run Code Online (Sandbox Code Playgroud)

上面的代码将html文件作为文件上传到Google云端硬盘,而不是将HTML呈现为Google文档.很公平,这是有道理的.但是我如何将其渲染为Google Doc,因为我可以使用Documents List API?

另一件事 - 如果我设置resumable = True它会在App Engine上抛出以下错误 - '_StreamSlice'没有len().无法弄清楚如何获得resumable = True工作?

最后一件事 - 文档中示例代码使用MediaInMemoryUpload对象,但是如果您查看源代码,它现在已被弃用,而是支持MediaIoBaseUpload.应该更新示例代码吗?!

pin*_*yid 7

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

  • 作为insert方法的参数传递.像这样的drive_service.files().insert(body = body,media_body = media_body,convert = True).execute().它在此处记录了https://developers.google.com/drive/v2/reference/files/insert (2认同)