Kyle's Place somewhere to put my thoughts

BytesIO to POST file with requests

I have been working on a project that prohibits me from saving files to disk. In my case, I needed to download an image from a website and upload that image elsewhere.

GET the file as a Byte Stream

This can be done using only requests and BytesIO; no need for Pillow or any other file manipulation modules! After getting the file through a GET request (r = requests.get(url)), read the response as bytes using r.content. These bytes can be used to create a BytesIO object file = BytesIO(r.content).

POST the file for upload

Now that you have a BytesIO object, requests can send that object as a file parameter. Use the getvalue() method to read the entire buffer of the BytesIO object. Create the files parameter for the requests encoded-file upload: files = { 'file':file.getvalue() }. Now that the parameters are ready, the file is ready for upload r = requests.post(url, files=files).

Putting it all together:

There you have it, upload a file without ever saving it to disk.