> Plain-text rendering of a visual post, for machine consumers.
> Charts, diagrams and images are omitted; their captions are kept inline.
> Titles on collapsible asides are dropped, their contents kept.
> The complete version is at https://abhay.fyi/blog/set-a-retry-strategy-for-python-requests/

# Set a retry strategy for Python requests

> This shows how to set a retry strategy for Python requests.

- Author: Abhay Kashyap (https://abhay.fyi/#person)
- Published: 2022-10-05
- Canonical: https://abhay.fyi/blog/set-a-retry-strategy-for-python-requests/

---
If you're overly enthuiastic with your requests to a server, it can get passive aggressive and give you the silent treatment or get overwhelmed and ask for a vacation.
To mitigate that, give it some space with a `retry` strategy.
Here's one such strategy with Python's `requests` package.

```python
import requests
from requests.adapters import HTTPAdapter, Retry

max_retries = Retry(
    total=3,
    allowed_methods=False,
    status_forcelist=[408, 429, 500, 502, 503, 504],
    backoff_factor=1,
)
adapter = HTTPAdapter(max_retries=max_retries)
http = requests.Session()
http.mount("https://", adapter)
http.mount("http://", adapter)

resp = http.get("https://i.imgur.com/AD3MbBi.jpeg")
```

---

### references

- [Urllib3](https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#module-urllib3.util.retry)
- [Python requests advanced usage](https://findwork.dev/blog/advanced-usage-python-requests-timeouts-retries-hooks/)