TL;DR; Add a decorator to avoid server timeouts
When getting swisstopo altitude profiles the response time is in general quite good but just sometimes I ran into timeouts, be it due to my bad connection or too many requests to the server. To amend I added this decorator that you can get as the most up-to-date version from my GitHub gists to the original swisstopo function (or other functions that might run into some form of timeout)
def exponential_retry(max_retries, delay):
"""Retry a request with exponentially increasing (slightly random) time in between tries"""
"""Usage before def of another function via @exponential_retry(5, 1) """
def decorator_exponential_retry(func):
import functools
@functools.wraps(func)
def wrapper_exponential_retry_decorator(*args, **kwargs):
import random
retries = 0
while retries <= max_retries:
try:
return func(*args, **kwargs)
except Exception as e:
print(f"Attempt {retries + 1} failed: {e}")
retries += 1
sleeptime = (delay * 2 ** retries + random.uniform(0, 1))
print(f"Retrying in {sleeptime:.2f} seconds...")
time.sleep(sleeptime)
raise Exception("Maximum amount of retries reached, too many timeouts/errors.")
return wrapper_exponential_retry_decorator
return decorator_exponential_retry
@exponential_retry(5, 1)
def get_swisstopo_elevation_profile(...):
.# source code of get_swisstopo_elevation_profile
...