From 5c1162706bf9f54b152096d1470e4993414c9d21 Mon Sep 17 00:00:00 2001 From: Harmon Date: Sat, 20 Feb 2021 22:24:38 -0600 Subject: [PATCH] Add wait_for_async_finalize parameter for API.chunked_upload --- docs/api.rst | 12 ++++++++++-- tweepy/api.py | 13 ++++++++++--- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/docs/api.rst b/docs/api.rst index 4dd8ef3..9c719ef 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1322,8 +1322,11 @@ Media methods [additional_owners]) Use this to upload media to Twitter. - This automatically uses the chunked upload endpoints for videos. This calls either :func:`API.simple_upload` or :func:`API.chunked_upload`. + Chunked media upload is automatically used for videos. + If ``chunked`` is set or the media is a video, ``wait_for_async_finalize`` + can be specified as a keyword argument to be passed to + :func:`API.chunked_upload`. :param filename: |filename| :param file: |file| @@ -1351,16 +1354,21 @@ Media methods .. method:: API.chunked_upload(filename, [file], [file_type], \ - [media_category], [additional_owners]) + [wait_for_async_finalize], [media_category], \ + [additional_owners]) Use this to upload media to Twitter. This uses the chunked upload endpoints and calls :func:`API.chunked_upload_init`, :func:`API.chunked_upload_append`, and :func:`API.chunked_upload_finalize`. + If ``wait_for_async_finalize`` is set, this calls + :func:`API.get_media_upload_status` as well. :param filename: |filename| :param file: |file| :param file_type: The MIME type of the media being uploaded. + :param wait_for_async_finalize: Whether to wait for Twitter's API to finish + processing the media. Defaults to ``True``. :param media_category: |media_category| :param additional_owners: |additional_owners| diff --git a/tweepy/api.py b/tweepy/api.py index 933f07d..b011e99 100644 --- a/tweepy/api.py +++ b/tweepy/api.py @@ -370,7 +370,8 @@ class API: ) def chunked_upload(self, filename, *, file=None, file_type=None, - media_category=None, additional_owners=None, **kwargs): + wait_for_async_finalize=True, media_category=None, + additional_owners=None, **kwargs): """ :reference https://developer.twitter.com/en/docs/media/upload-media/uploading-media/chunked-media-upload """ fp = file or open(filename, 'rb') @@ -404,8 +405,14 @@ class API: ) fp.close() - # The FINALIZE command returns media information - return self.chunked_upload_finalize(media_id, **kwargs) + media = self.chunked_upload_finalize(media_id, **kwargs) + + if wait_for_async_finalize and hasattr(media, 'processing_info'): + while media.processing_info['state'] in ('pending', 'in_progress'): + time.sleep(media.processing_info['check_after_secs']) + media = self.get_media_upload_status(media.media_id, **kwargs) + + return media @payload('media') def chunked_upload_init(self, total_bytes, media_type, *, -- 2.25.1