How to upload documents with new python-gdata (2.0.16)?

纵然是瞬间 提交于 2019-12-06 14:42:46

问题


With python-gdata 2.0.14, I used the following pieces of code to create and upload documents:

# To create a document
import gdata.docs
import gdata.docs.client
from gdata.data import MediaSource

gdClient = gdata.docs.client.DocsClient(source="my-app")
gdClient.ssl = True
gdClient.ClientLogin("login", "pa$$word", gdClient.source)
ms = MediaSource(file_path="temp.html", content_type="text/html")
entry = gdClient.Upload(ms, "document title")
print "uploaded, url is", entry.GetAlternateLink().href

and

# To update a document
entry.title.text = "updated title"
entry = gdClient.Update(entry, media_source=ms, force=True)
print "updated, url is", entry.GetAlternateLink().href

However, this code does no longer work with python-gdata 2.0.16 because DocsClient class does no more have Upload and Update functions.

I tried to use this

# Try to create a document
gdClient = gdata.docs.client.DocsClient(source="my-app")
gdClient.ssl = True
gdClient.ClientLogin("login", "pa$$word", gdClient.source)
ms = MediaSource(file_path="temp.html", content_type="text/html")
entry = gdata.docs.data.Resource(type=gdata.docs.data.DOCUMENT_LABEL, title="document title")
self.resource = gdClient.CreateResource(entry, media=ms)

… but I get this error:

gdata.client.Unauthorized: Unauthorized - Server responded with: 401, 'Token invalid'

Can anybody tell me where's my mistake and how should I use that new API?

P.S. The documentation hasn't been updated and still uses the old-style code.


回答1:


I was having issues with this recently too. This worked for me:

import gdata.docs.data
import gdata.docs.client

client = gdata.docs.client.DocsClient(source='your-app')
client.api_version = "3"
client.ssl = True
client.ClientLogin("your@email.com", "password", client.source)

filePath = "/path/to/file"
newResource = gdata.docs.data.Resource(filePath, "document title")

media = gdata.data.MediaSource()
media.SetFileHandle(filePath, 'mime/type')

newDocument = client.CreateResource(newResource, create_uri=gdata.docs.client.RESOURCE_UPLOAD_URI, media=media)

Edit: Added the packages to import to avoid confusion



来源:https://stackoverflow.com/questions/9127758/how-to-upload-documents-with-new-python-gdata-2-0-16

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!