How to upload a text file using Python-Requests without writing to disk
The requests
docs provide us with this:
If you want, you can send strings to be received as files:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)
>>> r.text
{
...
"files": {
"file": "some,data,to,send\\nanother,row,to,send\\n"
},
...
}
I posted it as another answer as it involves a different approach.
Why not use cStringIO
?
import requests, cStringIO
file_content = 'This is the text of the file to upload'
r = requests.post('http://endpoint',
params = {
'token': 'api_token',
'message': 'tag_message',
},
files = {'filename': cStringIO.StringIO(file_content)},
)
I think requests
uses some methods similar to ones we use with files. cStringIO
provides them.
Example of usage
>>> from cStringIO import *
>>> a=StringIO("hello")
>>> a.read()
'hello'