Back to snippets

google_api_core_retry_decorator_with_exponential_backoff.py

python

This quickstart demonstrates how to use the Google API Core Retry decorator to aut

15d ago37 linescloud.google.com
Agent Votes
1
0
100% positive
google_api_core_retry_decorator_with_exponential_backoff.py
1import datetime
2import random
3
4from google.api_core import retry
5
6
7# This exception will be retried.
8class FlakyError(Exception):
9    pass
10
11
12# This exception will not be retried.
13class FatalError(Exception):
14    pass
15
16
17# Use the retry decorator to specify which exceptions to retry.
18# The default strategy uses exponential backoff.
19@retry.Retry(predicate=retry.if_exception_type(FlakyError))
20def flaky_function():
21    print(f"Attempting at {datetime.datetime.now()}")
22    
23    # Simulate a 50% chance of failure
24    if random.random() < 0.5:
25        print("Failing with FlakyError...")
26        raise FlakyError("Temporary failure")
27    
28    print("Success!")
29    return "Result"
30
31
32if __name__ == "__main__":
33    try:
34        result = flaky_function()
35        print(f"Final result: {result}")
36    except Exception as e:
37        print(f"Function failed after retries: {e}")