user12720904
user12720904

Reputation:

How to do a partial download in Google Drive Api v3?

The documentation says here that you need to use the Range header Range: bytes=500-999.

My code

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

How do I use the headers?

Upvotes: 3

Views: 1916

Answers (1)

Tanaike
Tanaike

Reputation: 201553

  • You want to achieve the partial download of the file from Google Drive using google-api-python-client with python.
  • You have already been able to download the file from Google Drive using Drive API with your script.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

  • In this case, the range property like Range: bytes=500-999 is required to be included in the request header. This has already been mentioned in your question.
    • For request = drive_service.files().get_media(fileId=file_id), it includes the range property in the header.

When your script is modified, it becomes as follows.

Modified script:

From:
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()
To:
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()

Note:

  • In above modified script, when MediaIoBaseDownload is used, it was found that the file is completely downloaded without using the range property. So I don't use MediaIoBaseDownload.
  • Also you can use requests like as follows.

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

Reference:

If I misunderstood your question and this was not the direction you want, I apologize.

Upvotes: 2

Related Questions