urllib2 POST进度监控

时间:2011-05-08 01:15:16

标签: python http urllib2 http-post

我正在通过POST将带有urllib2的相当大的文件上传到服务器端脚本。我想显示一个显示当前上传进度的进度指示器。是否有urllib2提供的钩子或回调,允许我监控上传进度?我知道你可以通过连续调用连接的read()方法来下载,但是我没有看到write()方法,你只需要向请求中添加数据。

4 个答案:

答案 0 :(得分:23)

这是可能的,但你需要做一些事情:

  • 假设urllib2子系统通过附加__len__属性将文件句柄传递给httplib,使len(data)返回正确的大小,用于填充Content-Length标头。
  • 覆盖文件句柄上的read()方法:当httplib调用read()时,系统会调用您的回调,让您计算百分比并更新进度条。

这可以用于任何类似文件的对象,但是我已经包装file以显示它如何与从磁盘流传输的非常大的文件一起工作:

import os, urllib2
from cStringIO import StringIO

class Progress(object):
    def __init__(self):
        self._seen = 0.0

    def update(self, total, size, name):
        self._seen += size
        pct = (self._seen / total) * 100.0
        print '%s progress: %.2f' % (name, pct)

class file_with_callback(file):
    def __init__(self, path, mode, callback, *args):
        file.__init__(self, path, mode)
        self.seek(0, os.SEEK_END)
        self._total = self.tell()
        self.seek(0)
        self._callback = callback
        self._args = args

    def __len__(self):
        return self._total

    def read(self, size):
        data = file.read(self, size)
        self._callback(self._total, len(data), *self._args)
        return data

path = 'large_file.txt'
progress = Progress()
stream = file_with_callback(path, 'rb', progress.update, path)
req = urllib2.Request(url, stream)
res = urllib2.urlopen(req)

输出:

large_file.txt progress: 0.68
large_file.txt progress: 1.36
large_file.txt progress: 2.04
large_file.txt progress: 2.72
large_file.txt progress: 3.40
...
large_file.txt progress: 99.20
large_file.txt progress: 99.87
large_file.txt progress: 100.00

答案 1 :(得分:1)

requests 2.0.0 has streaming uploads。这意味着您可以使用生成器来生成小块并在块之间打印进度。

答案 2 :(得分:0)

我认为这不可行,但您可以使用pycurl does have upload/download progress callbacks

答案 3 :(得分:0)

poster支持此

import json
import os
import sys
import urllib2

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers

def _upload_progress(param, current, total):
    sys.stdout.write(
        "\r{} - {:.0f}%                "
        .format(param.name,
                (float(current) / float(total)) * 100.0))
    sys.stdout.flush()

def upload(request_resource, large_file_path):
    register_openers()
    with open(large_file_path, 'r') as large_file:
        request_data, request_headers = multipart_encode(
            [('file', largs_file)],
            cb=_upload_progress)

        request_headers.update({
            'X-HockeyAppToken': 'we use this for hockeyapp upload'
        })

        upload_request = urllib2.Request(request_resource,
                                         request_data, 
                                         request_headers)
        upload_connection = urllib2.urlopen(upload_request)
        upload_response = json.load(upload_connection)
    print "Done"