@ -72,8 +72,9 @@ def get_location_by_coordinates_optimized(lat, lon):
lon_max = lon + lon_range
# Query with population weighting to prefer larger cities
# Debug query (optional - if fails, we continue without debug info)
try :
with connection . cursor ( ) as cursor :
# First, let's get debug information about nearby cities
cursor . execute ( """
WITH bounded_cities AS (
SELECT name , country_code , latitude , longitude , population
@ -103,9 +104,12 @@ def get_location_by_coordinates_optimized(lat, lon):
logger . info ( f " 🔍 Top 10 nearby cities for coordinates ({lat}, {lon}): " )
for name , cc , pop , dist in debug_results :
logger . info ( f " 📍 {name} ({cc}): population={pop:,}, distance={dist:.2f}km " )
except Exception as debug_error :
logger . warning ( f " ⚠️ Debug query failed for ({lat}, {lon}): {str(debug_error)} " )
# Continue without debug info - this is not critical
# Now get the best city using a weighted approach
# Prefer cities with larger population within reasonable distance
# Main query - use separate cursor to avoid transaction issues
with connection . cursor ( ) as cursor :
cursor . execute ( """
WITH bounded_cities AS (
SELECT name , country_code , latitude , longitude , population
@ -163,7 +167,8 @@ def get_location_by_coordinates_optimized(lat, lon):
cache . set ( cache_key , None , 3600 )
return None
except Exception :
except Exception as e :
logger . warning ( f " ⚠️ Optimized method failed for ({lat}, {lon}): {str(e)} - trying fallback " )
# Fallback to original method on any error
return get_location_by_coordinates_original ( lat , lon )