From c73e7a27be67d570e9404db6fe664adf2a8aa6f4 Mon Sep 17 00:00:00 2001 From: Harmon Date: Wed, 19 May 2021 10:42:34 -0500 Subject: [PATCH] Properly close file in API.simple_upload --- tweepy/api.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/tweepy/api.py b/tweepy/api.py index f48d460..8acf89b 100644 --- a/tweepy/api.py +++ b/tweepy/api.py @@ -2570,21 +2570,22 @@ class API: :reference: https://developer.twitter.com/en/docs/twitter-api/v1/media/upload-media/api-reference/post-media-upload """ - if file is not None: - files = {'media': (filename, file)} - else: - files = {'media': open(filename, 'rb')} + with contextlib.ExitStack() as stack: + if file is not None: + files = {'media': (filename, file)} + else: + files = {'media': stack.enter_context(open(filename, 'rb'))} - post_data = {} - if media_category is not None: - post_data['media_category'] = media_category - if additional_owners is not None: - post_data['additional_owners'] = additional_owners + post_data = {} + if media_category is not None: + post_data['media_category'] = media_category + if additional_owners is not None: + post_data['additional_owners'] = additional_owners - return self.request( - 'POST', 'media/upload', post_data=post_data, files=files, - upload_api=True, **kwargs - ) + return self.request( + 'POST', 'media/upload', post_data=post_data, files=files, + upload_api=True, **kwargs + ) def chunked_upload(self, filename, *, file=None, file_type=None, wait_for_async_finalize=True, media_category=None, -- 2.25.1