2011-09-29 128 views
0

根据我的理解,我正在开发一个适用于Google API的应用程序。如何通过Google Data API将文件上传到Google文档?

def push_to_ga(request): 
    client = gdata.docs.service.DocsService() 
    client.ClientLogin('[email protected]', 'password') 

    entrys = Entry.objects.all() 
    for entry in entrys: 
     splitted = entry.file.split('/') 
     client.UploadDocument(entry.file, splitted[-1]) 

    return HttpResponseRedirect('https://docs.google.com/#home') 

有一个错误:

Traceback: File "/home/i159/Env/googleapi/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response 111. response = callback(request, *callback_args, **callback_kwargs) File "/home/i159/workspace/apiroot/googleapi/../googleapi/apiapp/views.py" in push_to_ga 38. client.UploadDocument(entry.file, 'My entry #' + str(entry.id)) File "/home/i159/Env/googleapi/lib/python2.6/site-packages/atom/init.py" in deprecated_function 1475. return f(*args, **kwargs) File "/home/i159/Env/googleapi/lib/python2.6/site-packages/gdata/docs/service.py" in UploadDocument 494. folder_or_uri=folder_or_uri) File "/home/i159/Env/googleapi/lib/python2.6/site-packages/gdata/docs/service.py" in _UploadFile 160. extra_headers={'Slug': media_source.file_name},

Exception Type: AttributeError at /push_to_ga/ Exception Value: 'unicode' object has no attribute 'file_name'

我无法找到的方法描述文档。如何通过API将文件上传到Google文档?

回答

1

您使用的是哪个版本的Google API?

按照Google documentation,1.0版本和2.0你必须文档包装为MediaSource对象,以便将其传递给上传方法。所以,我认为你需要更换:

client.UploadDocument(entry.file, splitted[-1]) 

有:

ms = gdata.MediaSource(file_path=entry.file, content_type=gdata.docs.service.SUPPORTED_FILETYPES['DOC']) 
client.Upload(ms, splitted[-1]) 

注:这假定您上传Word文件。对于您上传的每个文件,您应该将content_type参数设置为correct type

如果您使用version 3.0,您不再需要创建一个MediaSource的对象 - 你可以简单地直接传递的路径,标题和MIME类型的上传方法:

client.Upload(entry.file, splitted[-1], content_type='application/msword') 

上传PDF文件

如果您尝试使用API​​的2.0版上传PDF文件时,它失败,出现错误:

{'status': 415, 'body': 'Content-Type application/pdf is not a valid input type.', 'reason': 'Unsupported Media Type'} 

这可以使用Google代码网站上问题591上comment 77中显示的解决方法修复。简单地编辑site-packages/gdata/docs/services.py文件中的_UploadFile方法,如该故障单所示。一旦你做了这个改变,PDF上传应该工作正常(我已经检查了这个&它适用于我)。

+1

@ I159我看到了您对PDF文件的评论,并相应地更新了我的答案。 – msanders

相关问题