'Show the download speed in Google drive Python

How do I show the download speed in Google drive API Python

I want to modify it to show the download speed

def download_file(id):
    fileStats=file_info(id)
    # showing the file stats
    print("----------------------------")
    print("FileName: ",fileStats['name'])
    print("FileSize: ",convert_size(int(fileStats['size'])))
    print("----------------------------")

    request = service.files().get_media(fileId=id)
    fh = io.BytesIO()
    downloader = MediaIoBaseDownload(fh, request,chunksize=1048576)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        # just a function that clear the screen and displays the text passed as argument
        ui_update('{1:<10}\t{2:<10}\t{0}'.format(fileStats['name'],color(convert_size(int(fileStats['size'])),Colors.orange),color(f'{round(status.progress()*100,2)}%',Colors.green)))

        fh.seek(0)
        with open(os.path.join(location, fileStats['name']), 'wb') as f:
            f.write(fh.read())
            f.close()
    else:
        print("File Download Cancelled!!!")



Solution 1:[1]

You can just calculate the speed yourself. You know the chunk size, so you know how much is being downloaded; time the download speed.

Something like:

from time import monotonic
...
CHUNKSIZE=1048576
while not done:
    start = monotonic()
    status, done = downloader.next_chunk()
    speed = CHUNKSIZE / (monotonic() - start)

Or, depending on your gui, use a proper progress bar library (which will do something similar internally).

Note that horribly long lines are very difficult to read. This:

ui_update('{1:<10}\t{2:<10}\t{0}'.format(fileStats['name'],color(convert_size(int(fileStats['size'])),Colors.orange),color(f'{round(status.progress()*100,2)}%',Colors.green)))

Should be written more like this:

name = fileStats["name"]
size = color(convert_size(int(fileStats["size"])), Color.orange)
progress = round(status.progress() * 100, 2)
progress = color(f"{progress} %", colors.green)
ui_update('{1:<10}\t{2:<10}\t{0}'.format(name, size, progress))

Now we can read it, we can see that only the progress value ever changes. So move name and size outside your loop and only call them once.

References

https://docs.python.org/3/library/time.html#time.monotonic

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1