使用 Python 中的请求将文件上传到 Google Drive

Pet*_*sta 5 python google-api python-requests google-drive-api

我正在努力通过他们的 API 正确地将文件上传到 Google Drive。我正在使用 Python,并且我知道有一个用于 Google API 的客户端库。这是我目前拥有的。运行以下代码时,会在 Google Drive 中创建一个空的无标题文档,并且它不在正确的目录root/level_1. 我不确定我对dataandfiles对象做错了什么。代码中有什么值得注意的地方吗?

这是我正在关注的文档。

import json
import requests

url = "https://www.googleapis.com/upload/drive/v2/files?access_token=ACCESS_TOKEN&uploadType=multipart"
files = {"file": requests.get("image_url").content}
data = {
    "title": "image_url.jpg",
    "parents": ["root", "level_1"]
}

response = requests.post(url, data=json.dumps(data), files=files)
# json.loads(response.text)["title"] = "Untitled"
return response
Run Code Online (Sandbox Code Playgroud)

Rey*_*cia 0

我认为您无法在上传时设置目录,因此“root”将始终是默认目录。让它先上传到根文件夹,然后移动文件。有关使用 Python 的完整代码实现,请关注 Wesley Chun 的博客: 使用 Python 上传和下载文件

片段:

DRIVE = build('drive', 'v2', http=creds.authorize(Http()))

FILES = (
    ('hello.txt', False),
    ('hello.txt', True),
)
for filename, convert in FILES:
    metadata = {'title': filename}
    res = DRIVE.files().insert(convert=convert, body=metadata,
            media_body=filename, fields='mimeType,exportLinks').execute()
    if res:
        print('Uploaded "%s" (%s)' % (filename, res['mimeType']))
Run Code Online (Sandbox Code Playgroud)

另外,请查看官方Drive API 上传文件文档。

要选择上传文件夹,请查看此SO 帖子