Properly close file in API.update_profile_banner
authorHarmon <Harmon758@gmail.com>
Wed, 19 May 2021 15:42:18 +0000 (10:42 -0500)
committerHarmon <Harmon758@gmail.com>
Wed, 19 May 2021 15:42:18 +0000 (10:42 -0500)
tweepy/api.py

index 856e0ab752df4da2b3fbb452f4e74e7d44a12047..f48d46090657e4677e18d91cdf03d6bd5476a441 100644 (file)
@@ -2087,15 +2087,16 @@ class API:
 
         :reference: https://developer.twitter.com/en/docs/twitter-api/v1/accounts-and-users/manage-account-settings/api-reference/post-account-update_profile_banner
         """
-        if file is not None:
-            files = {'banner': (filename, file)}
-        else:
-            files = {'banner': open(filename, 'rb')}
-        return self.request(
-            'POST', 'account/update_profile_banner', endpoint_parameters=(
-                'width', 'height', 'offset_left', 'offset_top'
-            ), files=files, **kwargs
-        )
+        with contextlib.ExitStack() as stack:
+            if file is not None:
+                files = {'banner': (filename, file)}
+            else:
+                files = {'banner': stack.enter_context(open(filename, 'rb'))}
+            return self.request(
+                'POST', 'account/update_profile_banner', endpoint_parameters=(
+                    'width', 'height', 'offset_left', 'offset_top'
+                ), files=files, **kwargs
+            )
 
     @payload('user')
     def update_profile_image(self, filename, *, file=None, **kwargs):