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

Conversation

RichieB2B
Copy link
Contributor

@RichieB2B RichieB2B commented Feb 7, 2023

In the documentation for POST a Multipart-Encoded File the example code opens the file inline but never closes it. This leaves the file open until the script ends. It is better to use a context manager even in example code.

Original:

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

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

Replace with:

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

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

@lpaladin
Copy link

I've just got bitten by this example, and was just about to create a PR for this too 😃

(Maybe

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

could be

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants