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 Feb 7, 2023
1 parent 1558590 commit 4fd2167
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
11 changes: 6 additions & 5 deletions docs/user/advanced.rst
Original file line number Diff line number Diff line change
Expand Up @@ -399,11 +399,12 @@ 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)
>>> r.text
>>> 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
{
...
'files': {'images': 'data:image/png;base64,iVBORw ....'}
Expand Down
14 changes: 8 additions & 6 deletions docs/user/quickstart.rst
Original file line number Diff line number Diff line change
Expand Up @@ -303,10 +303,11 @@ 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, 'rb')}

>>> r = requests.post(url, files=files)
>>> r.text
... r = requests.post(url, files=files)
... r.text
{
...
"files": {
Expand All @@ -318,10 +319,11 @@ 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.text
... r = requests.post(url, files=files)
... r.text
{
...
"files": {
Expand Down

0 comments on commit 4fd2167

Please sign in to comment.