python上传文件到与我共享的google驱动器文件夹

时间:2013-10-25 08:19:01

标签: python google-drive-api

我正在使用Python 2.7,我正在尝试将文件(* .txt)上传到与我共享的文件夹中。

到目前为止,我能够将其上传到我的云端硬盘,但如何设置到哪个文件夹。我得到了必须放置此文件的网址。

谢谢

到目前为止这是我的代码

def Upload(file_name, file_path, upload_url):

    upload_url = upload_url
    client = gdata.docs.client.DocsClient(source=upload_url)
    client.api_version = "3"
    client.ssl = True
    client.ClientLogin(username,  passwd, client.source)

    filePath = file_path
    newResource = gdata.docs.data.Resource(filePath,file_name)

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

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

1 个答案:

答案 0 :(得分:5)

您正在使用的API已弃用。请改用google-api-python-client

按照此official python quickstart guide将文件上传到文件夹。另外,在请求正文中发送parent参数,如下所示:body['parents'] = [{'id': parent_id}]

或者,您可以使用PyDrive这个Python包装程序库,它简化了许多处理Google Drive API的工作。整个代码就像这样简单:

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive

gauth = GoogleAuth()
drive = GoogleDrive(gauth)

f = drive.CreateFile({'parent': parent_id})
f.SetContentFile('cat.png') # Read local file
f.Upload() # Upload it