From cabd270765b8da19376a3eae783aba15a3d012f9 Mon Sep 17 00:00:00 2001 From: Richard van den Berg Date: Wed, 29 Nov 2023 15:03:04 +0100 Subject: [PATCH] Use context manager to open files --- docs/user/advanced.rst | 9 +++++---- docs/user/quickstart.rst | 10 ++++++---- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/docs/user/advanced.rst b/docs/user/advanced.rst index c664a83d30..1a721c36d1 100644 --- a/docs/user/advanced.rst +++ b/docs/user/advanced.rst @@ -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 { ... diff --git a/docs/user/quickstart.rst b/docs/user/quickstart.rst index 7fac5ce735..54fe0b9ade 100644 --- a/docs/user/quickstart.rst +++ b/docs/user/quickstart.rst @@ -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 { ... @@ -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 { ...