1
1

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を使ってpostリクエストをretryする

Last updated at Posted at 2020-12-20

しょーもないハマり方をしてしまったので供養のためメモ

pythonのrequestsモジュールを使う際、リトライの処理を実装したいときはurllib3.utilのRetryが使えます。

今回postでステータスコード500が帰ってきた時に一定時間待ってからリトライする処理をさせたかったので、Retryを使ったのですが500番が返ってきてもリトライしてくれず...
結論を言うとpostでリトライさせたいときは引数のallowed_methos渡してをPOSTリクエストに関して明示的に許可してやる必要がありました。

test.py

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

logging.basicConfig(level=logging.DEBUG)

session = requests.Session()

retries = Retry(total=5,backoff_factor=1,allowed_methods=['POST'],status_forcelist = [500])
retries_default = Retry(total=5,backoff_factor=1,status_forcelist = [500])
logging.debug(repr(retries.__dict__))
logging.debug(repr(retries_default.__dict__)) #指定しないとallowed_methosにPOSTがない
session.mount('https://',HTTPAdapter(max_retries=retries))

session.post('https://httpbin.org/status/500')

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?