【问题标题】:Upload file to Google Drive with Requests in Python使用 Python 中的请求将文件上传到 Google Drive
【发布时间】:2018-02-09 23:07:46
【问题描述】:

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

这是我关注的docs

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

【问题讨论】:

  • data=data 工作吗?
  • @DanBradbury 这不起作用。

标签: python google-api google-drive-api python-requests


【解决方案1】:

这个修改怎么样?

修改点:

  • 当您使用 Drive API 时,访问令牌需要包含在标头中。
  • 当你想插入文件给你想要的父母时,请使用文件夹ID。
    • 文件夹 ID 是 #####https://drive.google.com/drive/folders/#####
    • 如果要将文件插入根文件夹,可以使用root作为ID。

修改后的脚本:

import json
import requests

headers = {"Authorization": "Bearer " + ACCESS_TOKEN}
para = {
    "title": "image_url.jpg",
    "parents": [{"id": "root"}, {"id": "### folder ID ###"}]
}
files = {
    "data": ("metadata", json.dumps(para), "application/json; charset=UTF-8"),
    "file": requests.get("image_url").content
}
response = requests.post("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart", headers=headers, files=files)

return response

注意:

  • 此修改后的脚本通过调整为您的脚本使用 Drive API v2。
  • 请注意以下几点。
    • 在这个修改后的脚本中,将从image_url检索到的图像文件上传到Google Drive的根文件夹和以### folder ID ###为文件名的文件夹“image_url.jpg”。
    • 在这种情况下,“image_url.jpg”有 2 个父级。因此,当其中一个被删除时,父母双方的文件都会被删除。
  • 使用本脚本时,请再次确认以下2点。
    • 是否启用 Drive API。
    • 访问令牌是否包括将文件上传到 Google Drive 的范围。

如果我误解了你的问题,我很抱歉。

【讨论】:

  • 如何获取access_token?我不理解他们的文档,每次我接近时都需要打开一个网页并确认身份验证。我想做我的 api 到 google-drive
  • @Jay Cee 我可以通过检查here 知道检索访问令牌和刷新令牌的方法。我已经发布了作为检索访问令牌的答案。 this 怎么样?如果这不是您想要的,我很抱歉。
  • @Jay Cee 很高兴您的问题得到了解决。感谢您的回复。
  • 感谢这帮助我了解如何通过请求上传文件。但是我怎么能用uploadType=resumable 做到这一点
  • @Yashik 谢谢你的评论。例如,这些信息对您的情况有用吗? Ref1Ref2 如果这些对您的情况没有帮助,我深表歉意。
【解决方案2】:

我不认为你可以在上传时设置目录,所以'root'将始终是默认值。让它先上传到根文件夹,然后移动文件。有关使用 Python 的完整代码实现,请关注 Wesley Chun 的博客: Uploading & Downloading files with Python:

sn-p:

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']))

另外,请查看官方Drive API Uploading Files 文档。

要选择上传文件夹,请查看SO post

【讨论】:

    【解决方案3】:
    import requests
    f = open("img.png", "r")
    files = {
      "metadata": ("",'{"name": "rhondu.png"}', 'application/json'),
        'laadu': ('', open('img.png', 'rb'), 'image/png')
    }
    file = [("",'{"name": "rhondu420.png"}', 'application/json'), ('', open('img.png', 'rb'), 'image/png', {'Expires': '0'})]
    url = "https://www.googleapis.com/upload/drive/v3/files?access_token=ya29.A0ARrdaM8rd7nXLkz39QxqZOJp_DyVqAkQ98WErWhkuBmsihgFIGQ6TKF5YvWmtamWZXVqQD_Ey10hVy-5nsJskibD7-5obCOvDzySMlhXInFIHzHWJrONHXpO-l8JQ6UODgxHJermFEbvpAC20WMX5mPRAqRxoA"``
    res = requests.post(url, files=files)
    print(res.text) (edited) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-03-10
      • 2015-09-13
      • 2012-12-16
      • 1970-01-01
      相关资源
      最近更新 更多