将Python文件上传至Azure并获得进度

3

i'm uploading files to azure like so:

with open(tempfile, "rb") as data:
    blob_client.upload_blob(data, blob_type='BlockBlob',  length=None, metadata=None)

如何获取进度指示?
当我尝试以流的形式上传时,只上传了一个数据块。
我确定我做错了什么,但是找不到相关信息。
谢谢!
2个回答

6

看起来Azure库没有包含一个回调函数来监测进度。

幸运的是,你可以在Python文件对象周围添加一个包装器,每次读取时都会调用一个回调函数。

试试这个:

import os
from io import BufferedReader, FileIO


class ProgressFile(BufferedReader):
    # For binary opening only

    def __init__(self, filename, read_callback):
        f = FileIO(file=filename, mode='r')
        self._read_callback = read_callback
        super().__init__(raw=f)

        # I prefer Pathlib but this should still support 2.x
        self.length = os.stat(filename).st_size

    def read(self, size=None):
        calc_sz = size
        if not calc_sz:
            calc_sz = self.length - self.tell()
        self._read_callback(position=self.tell(), read_size=calc_sz, total=self.length)
        return super(ProgressFile, self).read(size)



def my_callback(position, read_size, total):
    # Write your own callback. You could convert the absolute values to percentages
    
    # Using .format rather than f'' for compatibility
    print("position: {position}, read_size: {read_size}, total: {total}".format(position=position,
                                                                                read_size=read_size,
                                                                                total=total))


myfile = ProgressFile(filename='mybigfile.txt', read_callback=my_callback)

那么你应该这样做

blob_client.upload_blob(myfile, blob_type='BlockBlob',  length=None, metadata=None)

myfile.close()

编辑: 看起来TQDM(进度监控器)有一个不错的包装器:https://github.com/tqdm/tqdm#hooks-and-callbacks。优点是你可以轻松地访问一个漂亮的进度条。


@Benny,我刚刚添加了TQDM的详细信息,它与现有解决方案类似,但增加了进度条的好处。 - Alastair McCormack

3
这就是我最终使用Alastair上面提到的tqdm包装器的方式。
  from tqdm import tqdm

  size = os.stat(fname).st_size
  with tqdm.wrapattr(open(fname, 'rb'), "read", total=size) as data:
     blob_client.upload_blob(data)

完美运作,显示时间估计、进度条、易读的文件大小和传输速度。

这对我有用,很好的解决方案。只是为了澄清,你还可以添加:from tqdm import tqdm - Pedram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接