【问题标题】:How to monitor progress of a HTTP PUT upload using Python Requests and Clint如何使用 Python 请求和 Clint 监控 HTTP PUT 上传的进度
【发布时间】:2015-04-15 12:56:40
【问题描述】:

我正在编写一个简单的命令行应用程序 - transfer.py - 允许使用 HTTP 的“请求”库从 transfer.sh 服务上传和下载文件作为学习练习。感谢这里的一些答案,我能够使用 python-clint 和 python-requests 实现一个进度条来监控文件下载 - 所说的功能可以看到here

无论如何,当我尝试实现相同类型的进度条来监控上传时,我非常非常迷茫——它使用 HTTP PUT。我从概念上理解它应该非常相似,但由于某种原因无法弄清楚,如果有人能指出我正确的方向,我将不胜感激。我尝试了一些使用多部分编码器之类的方法,但这些方法会导致文件在上升过程中被破坏(服务接受原始 PUT 请求,并且多部分编码似乎把它弄乱了)。

最终目标是编写一个脚本,用随机密钥对要上传的文件进行AES加密,上传到服务,打印一个链接+加密密钥,供朋友下载/解密文件,主要是为了好玩并填补我的 python 中的一些知识空白。

【问题讨论】:

    标签: python progress put clint


    【解决方案1】:

    我建议您将requests_toolbeltclint.textui.progress 模块一起使用。我找到了这段代码。

    from clint.textui.progress import Bar as ProgressBar
    from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
    
    import requests
    
    
    def create_callback(encoder):
        encoder_len = encoder.len
        bar = ProgressBar(expected_size=encoder_len, filled_char='=')
    
        def callback(monitor):
            bar.show(monitor.bytes_read)
    
        return callback
    
    
    def create_upload():
        return MultipartEncoder({
            'form_field': 'value',
            'another_form_field': 'another value',
            'first_file': ('progress_bar.py', open(__file__, 'rb'), 'text/plain'),
            'second_file': ('progress_bar.py', open(__file__, 'rb'),
                            'text/plain'),
            })
    
    
    if __name__ == '__main__':
        encoder = create_upload()
        callback = create_callback(encoder)
        monitor = MultipartEncoderMonitor(encoder, callback)
        r = requests.post('https://httpbin.org/post', data=monitor,
                          headers={'Content-Type': monitor.content_type})
        print('\nUpload finished! (Returned status {0} {1})'.format(
            r.status_code, r.reason
            ))
    

    【讨论】:

    • 对于它的价值,上面的代码做了一个 POST(不是 PUT)。到目前为止,我非常简短的调查表明,PUT 无法正常工作(至少不会调用进度回调)。
    • 你是对的。我不知道 3 个人怎么会投票给无法回答问题的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 2012-08-03
    相关资源
    最近更新 更多