Python - using requests with retry

less than 1 minute read

The following example will show how to create a request session with retries.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

def create_session(retry, back_off):
    retry_strategy = Retry(
        total=retry,
        connect=retry,
        read=retry,
        backoff_factor=back_off,
        # status_forcelist=[429, 500, 502, 503, 504],
        # method_whitelist=["HEAD", "GET", "OPTIONS"]
    )
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session = requests.Session()
    session.mount("https://", adapter)
    session.mount("http://", adapter)

    return session

Calling API with a created session

1
2
3
4
5
6
7
8
9
session = create_session(3, 0.1)
url = f"https://{host_name}:{port}/api/test"
headers = {'Content-type': 'application/json'}
payload = r'{ "data": "payload test" }'
data = session.post(url,
                    verify=False,
                    headers=headers,
                    data=payload)
print(data.text)

Categories:

Updated: