python - 如何在 Google Drive Api v3 中进行部分下载?

标签 python download header google-drive-api

文档说 here您需要使用范围 header Range: bytes=500-999

我的代码

def downloadChunkFromFile(file_id, start, length):
    headers = {"Range": "bytes={}-{}".format(start, start+length)}
    #How do I insert the headers?
    request = drive_service.files().get_media(fileId=file_id)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request, chunksize=length)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
    return fh.getvalue()

如何使用 header ?

最佳答案

  • 您想使用带有 python 的 google-api-python-client 从 Google 云端硬盘部分下载文件。
  • 您已经能够通过脚本使用 Drive API 从 Google Drive 下载文件。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能的答案之一。

修改点:

  • 在这种情况下,请求 header 中需要包含 Range: bytes=500-999 等范围属性。这在你的问题中已经提到了。
    • 对于 request = drive_service.files().get_media(fileId=file_id),它在 header 中包含范围属性。

当你的脚本修改后,变成如下。

修改后的脚本:

从:
request = drive_service.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request, chunksize=length)
done = False
while done is False:
    status, done = downloader.next_chunk()
return fh.getvalue()
到:
request = drive_service.files().get_media(fileId=file_id)
request.headers["Range"] = "bytes={}-{}".format(start, start+length)
fh = io.BytesIO(request.execute())
return fh.getvalue()

备注:

  • 在上面修改的脚本中,当使用MediaIoBaseDownload时,发现没有使用range属性就完全下载了文件。所以我不使用 MediaIoBaseDownload
  • 您也可以像下面这样使用请求

    url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
    headers = {"Authorization": "Bearer ###accessToken###", "Range": "bytes={}-{}".format(start, start+length)}
    res = requests.get(url, headers=headers)
    fh = io.BytesIO(res.content)
    return fh.getvalue()
    

引用:

如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

关于python - 如何在 Google Drive Api v3 中进行部分下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59763613/

相关文章:

python WatchedFileHandler 旋转后仍在写入旧文件

python - 并非所有参数在字符串格式化期间都已转换。没有 % 变量

iphone - 如何从 iOS 主线程上的 UIProgressBar 更新

go - 如何下载支持简历的文件?

c - make 出了什么问题?

python - 如何获取 BeautifulSoup 中子元素的 HTML 表示形式?

python - 如何在Azure逻辑应用程序中部署python?

javascript - 使用 javascript 启动下载

iphone - 如何更改sectionIndexTitlesForTableView 字母的颜色?在iphone上可以吗?

image - 通过 http 加载的图像的大小(宽度、高度)