Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a text file using Python-Requests without writing to disk

I would like to send a file in a POST request using Python's Requests library, in Python 3. I'm trying to send it like so:

import requests

file_content = 'This is the text of the file to upload'

r = requests.post('http://endpoint',
    params = {
        'token': 'api_token',
        'message': 'message text',
    },
    files = {'filename': file_content},
)

The server responds that no files were sent, however. Should this work? Most examples involve passing a file object, but I don't want to have to write the string out to disk just to upload it.

like image 479
Dov Avatar asked Apr 21 '15 18:04

Dov


People also ask

How do you upload a file in Python?

Method 1: Using the Python's os Module: Also, the enctype attribute with "multi-part/form-data" value will help the HTML form to upload a file. Lastly, we need the input tag with the filename attribute to upload the file we want. Lastly, we need the input tag with the filename attribute to upload the file we want.

How do I save a response to a text file in Python?

When writing responses to file you need to use the open function with the appropriate file write mode. For text responses you need to use "w" - plain write mode. For binary responses you need to use "wb" - binary write mode.

How do you send data to a file in Python?

We can use the write() method to put the contents of a string into a file or use writelines() if we have a sequence of text to put into the file. For CSV and JSON data, we can use special functions that Python provides to write data to a file once the file is open.


1 Answers

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.

like image 104
ForceBru Avatar answered Nov 02 '22 06:11

ForceBru