Created
June 19, 2015 20:02
-
-
Save ctoth/ec421390a2acccfc334e to your computer and use it in GitHub Desktop.
Uploading with requests_toolbelt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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