Skip to content

Instantly share code, notes, and snippets.

@mschulz
Created May 31, 2025 02:38
Show Gist options
  • Save mschulz/23fd7344e35ab36c8034ac2c4aa0117a to your computer and use it in GitHub Desktop.
Save mschulz/23fd7344e35ab36c8034ac2c4aa0117a to your computer and use it in GitHub Desktop.
gspread retry on 503 error
import gspread
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception
from requests.exceptions import HTTPError
def is_503_error(exception):
if isinstance(exception, HTTPError) and exception.response is not None:
return exception.response.status_code == 503
return False
@retry(
retry=retry_if_exception(is_503_error),
stop=stop_after_attempt(5),
wait=wait_exponential(multiplier=1, min=2, max=10)
)
def get_worksheet(spreadsheet_id, worksheet_name):
gc = gspread.service_account()
sh = gc.open_by_key(spreadsheet_id)
return sh.worksheet(worksheet_name)
# Example usage
try:
ws = get_worksheet('your_spreadsheet_id_here', 'Sheet1')
print(ws.get_all_records())
except Exception as e:
print("Failed to fetch worksheet:", e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment