0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

指数バックオフ

Last updated at Posted at 2022-05-10

google.api_core.retry を使って指数バックオフを行う方法

正直なところ、これで良いのかちょっとわからない。

ロジックでやりたい場合

from google.api_core.exceptions import TooManyRequests
from google.api_core import retry

_BACKOFF_DURATION = 200

@retry.Retry(predicate=retry.if_exception_type(AssertionError), deadline=_BACKOFF_DURATION)
def example_function():
		[なんか処理]
    if [指数バックオフでリトライしたい判定]:
        print('失敗')
        raise AssertionError('失敗')

GoogleCloudStorageでやりたい場合

GoogleCloudStorageにアップロードする場合、頻繁にするとTooManyRequestsが発生してしまうので、その場合は指数バックオフでリトライする

※このサンプルプログラムだと頻繁にアップロードにならないけど…

from google.cloud import storage
from google.cloud.storage.retry import DEFAULT_RETRY

_BACKOFF_DURATION = 200

def create_blob(bucket_name, file_name):
	client = storage.Client()
	bucket = _client.bucket(bucket_name)
    upload_blob = bucket.blob(file_name)
		return upload_blob

def upload_from_filename(upload_blob, file_name):
    # Customize retry with a deadline of 200 seconds (default=120 seconds).
    modified_retry = DEFAULT_RETRY.with_deadline(_BACKOFF_DURATION)
    upload_blob.upload_from_filename(file_name, retry=modified_retry)

if __name__ == '__main__':
    args = sys.argv
    if 3 <= len(args):
        if args[1].isascii:
            bucket_name = args[1]
            file_name = args[2]
        else:
            print('Argument is not bucket name')
            exit()
    upload_blob = create_blob(bucket_name, file_name)
	upload_from_filename(upload_blob, file_name)

参考

google-api-core
google-cloud-storage
再試行方法 | Cloud Storage | Google Cloud

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?