search
LoginSignup
0

posted at

updated at

指数バックオフ

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

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
What you can do with signing up
0