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

Python 如何在Google Drive Api v3中进行部分下载?,python,download,header,google-drive-api,Python,Download,Header,Google Drive Api,文档说明您需要使用范围标题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

文档说明您需要使用范围标题
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()
如何使用标题?

  • 您希望使用带有python的GoogleAPI python客户端从GoogleDrive实现文件的部分下载
  • 您已经能够在脚本中使用驱动API从Google Drive下载该文件
如果我的理解是正确的,那么这个答案呢?请把这看作是几个可能的答案之一

修改点:
  • 在这种情况下,请求标头中需要包含范围属性,如
    range:bytes=500-999
    。你的问题中已经提到了这一点。
    • 对于
      request=drive\u service.files().get\u media(fileId=file\u id)
      ,它在标头中包含range属性
当您的脚本被修改时,它将变成如下所示

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()
修改脚本: 发件人: 致: 注:
  • 在上面修改的脚本中,当使用
    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()
    
参考:
如果我误解了你的问题,而这不是你想要的方向,我道歉

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()