46
41

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 3 years have passed since last update.

python requestsでリトライ処理をする

Last updated at Posted at 2017-08-22

ソース: https://stackoverflow.com/a/35504626

backoff_factorで指定した秒数xリトライ回数の分だけ間隔を空けてリトライしてくれる。以下の場合はリトライ1回目は1秒、2回目は2秒。
status_forcelistで指定されたステータスコードが返ってきた場合、もしくはタイムアウトした時にリトライする。
Retryへ指定できるパラメータはここに書いてある。

import requests
from requests.packages.urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter

s = requests.Session()

retries = Retry(total=5,
                backoff_factor=1,
                status_forcelist=[ 500, 502, 503, 504 ])

s.mount('https://', HTTPAdapter(max_retries=retries))
s.mount('http://', HTTPAdapter(max_retries=retries))


r = s.request('GET', 'http://localhost:5000', timeout=2, headers={'Authorization': 'foobar'})
r.raise_for_status()

追記

retryというライブラリ使えば行けそう!と思ったけど、このライブラリだとステータスコードによる処理の振り分けとかができないみたい。

46
41
1

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
46
41

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?