Created
July 16, 2023 01:40
-
-
Save ashleymavericks/3ed96d0033ed4aa95a136c35b7b359b2 to your computer and use it in GitHub Desktop.
Quick pattern to handle exceptions with requests module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import sys | |
from http import HTTPStatus | |
import requests | |
from requests.exceptions import HTTPError | |
url = "https://theurl.com" | |
retries = 3 | |
retry_codes = [ | |
HTTPStatus.TOO_MANY_REQUESTS, | |
HTTPStatus.INTERNAL_SERVER_ERROR, | |
HTTPStatus.BAD_GATEWAY, | |
HTTPStatus.SERVICE_UNAVAILABLE, | |
HTTPStatus.GATEWAY_TIMEOUT, | |
] | |
for n in range(retries): | |
try: | |
response = requests.get(url) | |
response.raise_for_status() | |
break | |
except HTTPError as exc: | |
code = exc.response.status_code | |
if code in retry_codes: | |
# retry after n seconds | |
time.sleep(n) | |
continue | |
sys.exit(f"Status Code: {response.status_code} | Reason: {response.reason}") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment