Python requests send string as file

In my code, I am currently splitting a file and sending it a read to a temporary file, and then passing that temporary file to requests. Is there any way to send this message

with open(full_path, 'r+b') as f: i=0 while True: chunk = f.read(max_chunk_size) if not chunk: break with tempfile.TemporaryFile() as t: t.write(chunk) t.seek(0) r = requests.post(endpoint + 'upload_chunk', files={'chunk':t}, data={'mod_time':file_update_time, 'directory':'/'.join(subdirs), 'filename':filename, 'chunk_pos':i}, auth=auth) i+=max_chunk_size 

Is there a way to send a piece to the server without writing it to a temporary file and then read something in request.post this file? I would prefer not to change the code on the server side. I believe that there is no need to read / write additional 4 megabytes, it will increase the speed of execution.

Data exchange required; this code is not yet complete.

+7
source share
1 answer

Read the quick launch request page in the POST a Multipart-Encoded File section.

There you will find this:

If you want, you can send strings to receive 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" }, ... } 

Note that "file" is the name of the file upload field that the server expects. This will match the following HTML:

 <input type="file" name="file"> 
+9
source

Source: https://habr.com/ru/post/971399/


All Articles