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 –