Skip to content

Instantly share code, notes, and snippets.

@ashleymavericks
Created July 16, 2023 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashleymavericks/3ed96d0033ed4aa95a136c35b7b359b2 to your computer and use it in GitHub Desktop.
Save ashleymavericks/3ed96d0033ed4aa95a136c35b7b359b2 to your computer and use it in GitHub Desktop.
Quick pattern to handle exceptions with requests module
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