psf / requests

A simple, yet elegant, HTTP library.
https://requests.readthedocs.io/en/latest/
Apache License 2.0
52.19k stars 9.33k forks source link

Unclear file handling in documentation examples #6748

Closed daniboygg closed 4 months ago

daniboygg commented 5 months ago

In the Requests documentation section on posting multiple multipart-encoded files (https://requests.readthedocs.io/en/latest/user/advanced/#post-multiple-multipart-encoded-files), the files are opened but not explicitly closed:

url = 'https://httpbin.org/post'

multiple_files = [

    ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),

    ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]

r = requests.post(url, files=multiple_files)

r.text
{
  ...
  'files': {'images': 'data:image/png;base64,iVBORw ....'}
  'Content-Type': 'multipart/form-data; boundary=3131623adb2043caaeb5538cc7aa0b3a',
  ...
}

Does the library internally close the file handle during the post request?

After trying some simple examples, I found that the file does not close automatically. Would it be worth considering a mention in the documentation that users should close the file, or perhaps updating the example to demonstrate this scenario?

sigmavirus24 commented 5 months ago

Is it necessary to mention every possible best practice a person must follow when writing python in any section of the documentation? I really don't believe we must explain that as people should already be able to understand best practices around managing open files.

What made you assume requests would close the file for you? Why did that seem like a reasonable assumption?

daniboygg commented 5 months ago

When I was reading the documentation, it wasn't clear to me what the library exactly did with the file after passing it. After testing it out, I understood better and felt this might be a question other developers would ask too. I do get that this could make the examples a bit less straightforward, though. Thanks for taking the time to respond to me.