Junior — Middle
What methods can be used to quickly restore query execution in case of failure or delay?
sobes.tech AI
Answer from AI
For quick recovery of request execution in case of failure or delay in Python, several approaches can be used:
-
Retries
- Wrap the call in a loop with a limited number of attempts.
- Use libraries such as
retryingortenacity, which allow flexible retry configurations with delays.
-
Timeouts
- Set timeouts for network requests (for example, in
requestsvia thetimeoutparameter), to avoid waiting indefinitely.
- Set timeouts for network requests (for example, in
-
Asynchronous execution
- Use
asyncioto perform requests with the ability to cancel or switch to other tasks.
- Use
-
Exception handling
- Catch exceptions related to network errors or timeouts, and make retry attempts.
Example using the tenacity library:
from tenacity import retry, stop_after_attempt, wait_fixed
import requests
@retry(stop=stop_after_attempt(3), wait=wait_fixed(2))
def fetch_url(url):
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.text
try:
data = fetch_url('https://example.com')
except Exception as e:
print(f"Failed to retrieve data: {e}")
This code will attempt to perform the request up to 3 times with a 2-second pause between attempts.