Skip to content

Instantly share code, notes, and snippets.

@ctoth
Created June 19, 2015 20:02
Show Gist options
  • Select an option

  • Save ctoth/ec421390a2acccfc334e to your computer and use it in GitHub Desktop.

Select an option

Save ctoth/ec421390a2acccfc334e to your computer and use it in GitHub Desktop.
Uploading with requests_toolbelt
import os
import requests
from requests_toolbelt import MultipartEncoder, MultipartEncoderMonitor
def upload(filename, url, key='file', user_agent='HTTP-UPLOADER/1.0', callback=None):
total_size = os.stat(filename).st_size
payload = {key: (filename, open(filename, 'rb'), "application/octet-stream")}
encoder = MultipartEncoder(fields=payload, encoding='ascii')
def encoder_callback(mon):
if callback is not None:
callback(mon.bytes_read, total_size)
monitor = MultipartEncoderMonitor(encoder, encoder_callback)
headers = {'content-type': monitor.content_type, 'user-agent': user_agent}
r = requests.post(url, data=monitor, headers=headers)
r.raise_for_status()
return r.content
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment