Skip to content

Instantly share code, notes, and snippets.

@yejianye
Created June 19, 2014 05:18
Show Gist options
  • Save yejianye/3b08730d4ed31ae18c7d to your computer and use it in GitHub Desktop.
Save yejianye/3b08730d4ed31ae18c7d to your computer and use it in GitHub Desktop.
Show progress bar when uploading a file
# -*- coding: utf-8 -*-
# ############################################################################
# This example demonstrates how to use the MultipartEncoderMonitor to create a
# progress bar using clint.
# ############################################################################
from clint.textui.progress import Bar as ProgressBar
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
import requests
def create_callback(encoder):
encoder_len = len(encoder)
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
))
@arianhosseini
Copy link

I tried your code gives me this error:

encoder_len = len(encoder)
TypeError: object of type 'MultipartEncoder' has no len()

@mrthevinh
Copy link

replace
encoder_len = len(encoder)
by
encoder_len = encoder.len

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment