Skip to content

Commit

Permalink
Use context manager to open files
Browse files Browse the repository at this point in the history
  • Loading branch information
RichieB2B committed Nov 29, 2023
1 parent 1558590 commit cabd270
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
9 changes: 5 additions & 4 deletions docs/user/advanced.rst
Expand Up @@ -399,10 +399,11 @@ upload image files to an HTML form with a multiple file field 'images'::
To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::

>>> 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)
>>> with open('foo.png', 'rb') as fd1, open('bar.png', 'rb') as fd2:
... multiple_files = [
... ('images', ('foo.png', fd1, 'image/png')),
... ('images', ('bar.png', fd2, 'image/png'))]
... r = requests.post(url, files=multiple_files)
>>> r.text
{
...
Expand Down
10 changes: 6 additions & 4 deletions docs/user/quickstart.rst
Expand Up @@ -303,9 +303,10 @@ POST a Multipart-Encoded File
Requests makes it simple to upload Multipart-encoded files::

>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> with open('report.xls', 'rb') as fd:
... files = {'file': fd}

>>> r = requests.post(url, files=files)
... r = requests.post(url, files=files)
>>> r.text
{
...
Expand All @@ -318,9 +319,10 @@ Requests makes it simple to upload Multipart-encoded files::
You can set the filename, content_type and headers explicitly::

>>> url = 'https://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
>>> with open('report.xls', 'rb') as fd:
... files = {'file': ('report.xls', fd, 'application/vnd.ms-excel', {'Expires': '0'})}

>>> r = requests.post(url, files=files)
... r = requests.post(url, files=files)
>>> r.text
{
...
Expand Down

0 comments on commit cabd270

Please sign in to comment.