使用数据上传多行.text文件会产生503错误

时间:2014-09-25 03:15:26

标签: python google-drive-api

我的代码会使用gdata将单行.txt文件上传到我的Google云端硬盘。相同的文件,但换行字符不会上传并给出:

gdata.client.RequestError: Server responded with: 503,

删除换行符,它就可以了。知道如何解决这个问题吗?

编辑添加工作示例:

import sys 
import time 
import os.path
import atom.data
import gdata.client, gdata.docs.client, gdata.docs.data
import urllib2

class GoogleDriveFileUpload:

    def __init__(self, fileName, targetFolder, username, password, ftype='txt'):

        self.fileName = fileName
        self.targetFolder = targetFolder
        self.username = username
        self.password = password
        self.file_type = self.cvtFileType(ftype)


    def cvtFileType(self, ftype):
        if ftype == 'jpg':
            file_type = 'image/jpeg'
        elif ftype == 'kml':
            file_type = 'application/vnd.google-earth.kml+xml'
        elif ftype == 'txt':
            file_type = 'text/plain'
        elif ftype == 'csv':
            file_type = 'text/csv'
        elif ftype == 'mpg':
            file_type = 'audio/mpeg'
        elif ftype == 'mp4':
            file_type = 'video/mp4'

        return file_type

    def changeFile(self, fileName, ftype = 'txt'):
        self.fileName = fileName
        self.file_type = cvtFileType(ftype)
        self.file_size = os.path.getsize(fhandle.name)

    def changeTarget(self, targetFolder):
        self.targetFolder = targetFolder

    def upload(self):
        #Start the Google Drive Login
        docsclient = gdata.docs.client.DocsClient(source='GausLabAnalysis')

        # Get a list of all available resources (GetAllResources() requires >= gdata-2.0.15)
        # print 'Logging in...',
        try:
            docsclient.ClientLogin(self.username, self.password, docsclient.source);
        except (gdata.client.BadAuthentication, gdata.client.Error), e:
            sys.exit('Unknown Error: ' + str(e))
        except:
            sys.exit('Login Error. Check username/password credentials.')
        # print 'Success!'

        # The default root collection URI
        uri = 'https://docs.google.com/feeds/upload/create-session/default/private/full'
        # Get a list of all available resources (GetAllResources() requires >= gdata-2.0.15)
        # print 'Fetching Collection/Directory ID...',
        try:
           resources = docsclient.GetAllResources(uri='https://docs.google.com/feeds/default/private/full/-/folder?title=' + self.targetFolder + '&title-exact=true')
        except:
           sys.exit('ERROR: Unable to retrieve resources')
        # If no matching resources were found
        if not resources:
           sys.exit('Error: The collection "' + self.targetFolder + '" was not found.')
        # Set the collection URI
        uri = resources[0].get_resumable_create_media_link().href
        # print 'Success!'
        # Make sure Google doesn't try to do any conversion on the upload (e.g. convert images to documents)
        uri += '?convert=false'


        fhandle = open(self.fileName)
        self.file_size = os.path.getsize(fhandle.name)
        print 'Uploading ', self.fileName,'....' 
        # Create an uploader object and upload the file
        uploader = gdata.client.ResumableUploader(docsclient, fhandle, self.file_type, self.file_size, chunk_size=262144, desired_class=gdata.data.GDEntry)
        new_entry = uploader.UploadFile(uri, entry=gdata.data.GDEntry(title=atom.data.Title(text=os.path.basename(fhandle.name))))
        # print 'Success!',
        print 'File ' + self.fileName + ' uploaded to ' + self.targetFolder + ' at ' + time.strftime("%H:%M:%S %d/%m/%Y ", time.localtime()) + '.'


def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100', timeout=5)
        return True
    except:
        return False

def main():
    gdoc = GoogleDriveFileUpload('...\HelloWorld.txt', 'GoogleDriveFolderName', 'username', 'password') 
    if internet_on():
        gdoc.upload()


if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

当HelloWorld.txt为:

时,这种方法有效
Hello World!

但在同一文件为:

时因503错误而失败
Hello
World!

唯一的区别是记事本中添加的换行符。使用'\ n'而不是'\ r \ n'编写文件时的响应相同。

有什么方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

我自己解决了这个问题。我经历了使用新API设置事物的整个例程,但这会让您通过一个单独的Drive帐户然后共享文件而不是直接上传(从我可以工作的内容)。适合应用,但不适合我。

无法使用ResumableUploader类,但CreateResource似乎可以正常工作。

解决方法是删除

之后的两行
# Create an uploader object and upload the file

在上面的代码中添加

    mS = gdata.data.MediaSource(content_type = gdata.docs.service.SUPPORTED_FILETYPES[self.ftype.upper()])
    mS.SetFileHandle(self.fileName, self.file_type)
    doc = gdata.docs.data.Resource(type='file', title=os.path.basename(self.fileName))
    doc = docsclient.CreateResource(doc, media=mS, create_uri = uri)

就是这样!