0

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!!!")

bad_coder
  • 11,289
  • 20
  • 44
  • 72
blank
  • 1
  • 1
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Oct 01 '21 at 08:24

1 Answers1

0

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

2e0byo
  • 5,305
  • 1
  • 6
  • 26