@@ -764,12 +764,30 @@ async def _get_redis():
764764 global _redis_client
765765 if _redis_client is None :
766766 try :
767- _redis_client = redis .from_url (settings .REDIS_URL , decode_responses = True )
767+ _redis_client = redis .from_url (
768+ settings .REDIS_URL , decode_responses = True ,
769+ socket_connect_timeout = 2 , socket_timeout = 2 ,
770+ )
768771 except Exception :
769772 _redis_client = False
770773 return _redis_client if _redis_client is not False else None
771774
772775
776+ async def _cache_get (r , key : str ) -> dict | None :
777+ try :
778+ val = await r .get (key )
779+ return _json .loads (val ) if val else None
780+ except Exception :
781+ return None
782+
783+
784+ async def _cache_set (r , key : str , value : dict , ttl : int = 86400 ):
785+ try :
786+ await r .set (key , _json .dumps (value ), ex = ttl )
787+ except Exception :
788+ pass
789+
790+
773791@router .get ("/point" )
774792async def get_elevation_point (
775793 lat : float ,
@@ -784,9 +802,9 @@ async def get_elevation_point(
784802 r = await _get_redis ()
785803 cache_key = f"elev:{ lat_r } :{ lon_r } "
786804 if r :
787- cached = await r . get ( cache_key )
805+ cached = await _cache_get ( r , cache_key )
788806 if cached :
789- return _json . loads ( cached )
807+ return cached
790808
791809 # Static test data for well-known locations (WCS fallback)
792810 if lat_r == 42.817 and lon_r == - 1.642 :
@@ -842,8 +860,8 @@ async def get_elevation_point(
842860 "resolution_m" : int (dem .resolution .replace ("m" , "" )) if dem .resolution else None ,
843861 }
844862
845- # Cache for 24h
863+ # Cache for 24h (non-fatal if Redis is down)
846864 if r and result .get ("source" ) != "static" :
847- await r . set ( cache_key , _json . dumps ( result ), ex = 86400 )
865+ await _cache_set ( r , cache_key , result )
848866
849867 return result
0 commit comments