Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use context manager to open files #6347

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions docs/user/advanced.rst
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Loading