The before code waits indefinitely for the service response, risking hanging. The after code sets a 2-second timeout on the request. If the service does not respond in time, a Timeout exception is raised and handled gracefully with a fallback.
### Before (no timeout) ###
import requests
def call_service():
response = requests.get('http://service/api')
return response.text
### After (with timeout) ###
import requests
from requests.exceptions import Timeout
def call_service():
try:
response = requests.get('http://service/api', timeout=2) # 2 seconds timeout
return response.text
except Timeout:
return 'Service timed out, fallback response'