LoginSignup
15
15

More than 5 years have passed since last update.

Pythonでリトライ処理を実装する

Last updated at Posted at 2018-12-06

1. retryパッケージを使う

2. requestsでリトライの場合

ここら辺を参考に。
https://stackoverflow.com/questions/49121365/implementing-retry-for-requests-in-python

3. 自分で実装してみる

こんな感じ?

"""
例外発生時にリトライするシンプルな実装
常にリトライするのではなく、例外の内容を見てリトライするかどうか決定する
"""

import time


class MyException(Exception):
    def __init__(self, code):
        self.error_code = code


def do_task():
    raise MyException(code=1)


MAX_RETRY = 3


def do_with_retry():
    for i in range(MAX_RETRY + 1):
        try:
            do_task()
            return
        except MyException as e:
            # エラーコードが1のときだけリトライ
            if e.error_code == 1:
                print("エラー発生. retry={}/{}".format(i, MAX_RETRY))
                if i == MAX_RETRY:
                    raise e
                sleep_sec = 2 ** i
                print("sleep {} sec".format(sleep_sec))
                time.sleep(sleep_sec)
            else:
                print("エラー発生")
                raise e


if __name__ == '__main__':
    do_with_retry()

15
15
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
15
15