Bug in http.MediaIoBaseDownload
Problem is here. If content-range is not found in response. This will leads to infinite loop because self._total_size will always be None and self._progress == self._total_size will always results in False hence self._done will never be True. Shouldn't it raise an exception if content-range header is not found?
Although it is clearly mention here that the partial download is only available for file resources, which means that the range header should have been respected by the server but it doesn't which is quite surprising.
Steps to produce the problem:
- Create an empty file in Google Drive using the API.
- Download the file (using
http.MediaIoBaseDownload) with thedownloadUrlreturned by the file meta request.
This is not just related with Google Drive File Resources this is a general BUG. The http.MediaIoBaseDownload should make sure that the Range header is being respected, otherwise this defeat the whole purpose.
This is still an issue, and a serious one because it makes it impossible to download objects from Google Cloud Storage buckets using MediaIoBaseDownload.
Here's another way of getting objects (this does it in one go and stores it in memory, so may not be suitable for large files):
request = client.objects().get_media(bucket="blab", object="blab") response = request.execute() print response
This also applies to downloading via the Drive API, specifically mimeType Application/vnd.google-apps.* Thanks @musalbas your advice solved my problem.
I'm happy to accept/review any PRs to fix this issue.
We regularly test using MediaIoBaseDownload against Google Cloud Storage buckets, so I'm curious what your actual call pattern is to see what you might be doing differently. /cc @thobrla
@jonparrott ok thanks will take a look
@Capstan This code example fails as total_size is never defined, thus status is always False. This only occurs for the export_media function which does not provide a 'size' field. The get_media function does and has no issues.
file_id = '1ZdR3L3qP4Bkq8noWLJHSr_iBau0DNT4Kli4SxNc2YEo'
request = drive_service.files().export_media(fileId=file_id,
mimeType='application/pdf')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print "Download %d%%." % int(status.progress() * 100)
source: [https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents]
having the same issue as @markz0r Do we have any workaround to check completed exporting file?
I believe I am running into this issue too.
call pattern here:
media_body = MediaIoBaseUpload(fd, mime_type[0])
body = {
'title': name,
'mimeType': "application/vnd.google-apps.document",
}
service = _get_drive_service()
df = service.files().insert(
body=body,
media_body=media_body).execute()
request = service.files().export_media(fileId=df['id'], mimeType=DOCX_MIMETYPE)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
fh.seek(0)
return fh
maybe it has to do with inserting a vnd.google-apps.document file then immediately trying to export it?
Ran 1099 documents sequentially yesterday and 3 of them hit this infinite loop of doom.
Having this issue with get_media(). Solution proposed by @musalbas works for now.
For anyone looking for a work around:
def downloadFile(file_name, file_id, mimeType, service):
request = service.files().get_media(fileId=file_id)
if "application/vnd.google-apps" in mimeType:
if "document" in mimeType:
request = service.files().export_media(fileId=file_id, mimeType='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
file_name = file_name + ".docx"
else:
request = service.files().export_media(fileId=file_id, mimeType='application/pdf')
file_name = file_name + ".pdf"
print("Downloading -- " + file_name)
response = request.execute()
with open(os.path.join(OUTPUT_DIR, file_name), "wb") as wer:
wer.write(response)
Same here. Still happening. I ended up doing service.files().export(fileId=file_id, mimeType=mimeType).execute(http=http) but it's not ideal since the response is not buffered. A solution would be appreciated!
For those wanting to use a MediaIoBaseDownload, I also did what I describe here: http://stackoverflow.com/a/41643652/72350, which basically works as always for most requests, and just gets the first chunk for those incorrect responses (theoretically it might corrupt the file). Try it at your own risk.
Still happening as of March 2017, downloading files off Google Drive. The workarounds in this thread worked for me, but MediaIoBaseDownload is still listed as the correct method in the API documentation.
I'm not very knowledgeable about HTTP and the likes, but can't you just check if the received content is empty? Something like
if not content:
self._done = True
@Rawing no, you can't. I don't remember exactly when I debugged it, but it keeps receiving content, after the end of the file, but because it didn't receive the Content-Length, you don't know when it finished. There was no way to tell if content received is correct just looking at the content, that's what the Content-Length is for :)
@diegojancic So that means if this bug occurs, the program will write corrupt data to the file indefinitely? That actually makes this super harmful.
@Rawing Yes. I was keeping the file in memory, so it would make the run out of memory, but yes, it is that serious!
Check the example attached (google-api-bug-demo.zip). To execute, do the following:
pip install -r requirements.txt
pip install --upgrade google-api-python-client
python demo.py
The output will be something like this:
Running test with a file that works fine:
{'total_size': 57443, 'resumable_progress': 57443} - True
Running test with a file that does NOT work fine:
{'total_size': None, 'resumable_progress': 1231970} - False
{'total_size': None, 'resumable_progress': 2463941} - False
{'total_size': None, 'resumable_progress': 3695911} - False
{'total_size': None, 'resumable_progress': 4927881} - False
.
.
.
(never ends)
The second file is bigger because it contains some photos, but it also happens with small files. Because it happens in like 10% of the files, I don't have a smaller examples. Anyway, the problem as you can see is that the total_size is not being returned.
In the source, you can see that the total_size is set here:
if 'content-range' in resp:
content_range = resp['content-range']
length = content_range.rsplit('/', 1)[1]
self._total_size = int(length)
elif 'content-length' in resp:
self._total_size = int(resp['content-length'])
Which means that the _total_size is not being set because neither Content-Range nor Content-Length is being returned.
Note: the requirements.txt uses v1.6.0 of the API, but it also fails with 1.6.2.
Seeing the exact same behavior here with MediaIoBaseDownload and google drive documents.. Any update as to a fix or a priority from maintainers here?
Using google-api-python-client-1.6.4, still met the same issue, my code is like: ...
downloader = MediaIoBaseDownload(fh, request)
while done is False:
status, done = downloader.next_chunk()
print(downloader._total_size)
print(status.total_size)
print("Download %d" % int(status.progress() * 100))
... here the "total_size" is always "None" which leads "done" is always false. The target file is a 1580+ rows google spreadsheet. And it is so weird that if the file is less than 1580 rows then this issue will not happen. Hope anyone or API maintainer can help! Thanks!
The problem mostly happens to me when I am trying to download docs/sheets/ppt using mediaIoBaseDownload and it's necessary to use that when downloading big files.
So here's something that works for me
extension_type =
{ 'application/vnd.google-apps.presentation':['application/vnd.openxmlformats-officedocument.presentationml.presentation', 'ppt'],
'application/vnd.google-apps.spreadsheet': ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'xls'],
'application/vnd.google-apps.document': ['application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'docx']}
# rest codes in between for authentication and collecting files......
for item in items: # items is list of all the individual files
if item['mimeType'] not in extension_type:
request = service.files().get_media(fileId=item['id'])
open_file = item['name']
fh = open(open_file, mode='wb', buffering=8000)
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print (status.progress() * 100)
else:
request = service.files().export_media(fileId=item['id'],
mimeType=extension_type[item['mimeType']][0])
open_file = item['name'] + '.' + extension_type[item['mimeType']][1]
response = request.execute()
with open(open_file, "wb", 8000) as wer:
wer.write(response)
Should be handled by the latest commit.