如何使用Python请求和Clint监视HTTP PUT上载的进度

时间:2015-04-15 12:56:40

标签: python progress put clint

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

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

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

1 个答案:

答案 0 :(得分:2)

我建议您将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
        ))