67 lines
1.4 KiB
Python
67 lines
1.4 KiB
Python
import requests
|
|
import json
|
|
import os
|
|
|
|
API_URL = "https://geocoding-api.open-meteo.com/v1/search"
|
|
CITIES = ["Tel Aviv", "Beersheba", "Jerusalem", "Szeged"]
|
|
CACHE_FILE = "coordinates_cache.json"
|
|
|
|
|
|
def fetch_coordinates(city):
|
|
params = {
|
|
"name": city,
|
|
"count": 1
|
|
}
|
|
response = requests.get(API_URL, params=params)
|
|
response.raise_for_status()
|
|
data = response.json()
|
|
|
|
if "results" not in data:
|
|
raise ValueError(f"No results found for {city}")
|
|
|
|
result = data["results"][0]
|
|
|
|
return {
|
|
"name": result["name"],
|
|
"latitude": result["latitude"],
|
|
"longitude": result["longitude"],
|
|
"country": result["country"]
|
|
}
|
|
|
|
|
|
def load_cache():
|
|
if os.path.exists(CACHE_FILE):
|
|
with open(CACHE_FILE, "r") as f:
|
|
return json.load(f)
|
|
return None
|
|
|
|
|
|
def save_cache(data):
|
|
with open(CACHE_FILE, "w") as f:
|
|
json.dump(data, f, indent=4)
|
|
|
|
|
|
def main():
|
|
# Try loading cached data first
|
|
cached_data = load_cache()
|
|
if cached_data:
|
|
print("Loaded from cache:")
|
|
print(json.dumps(cached_data, indent=4))
|
|
return
|
|
|
|
# If no cache, fetch from API
|
|
print("Fetching from Open-Meteo API...")
|
|
results = {}
|
|
|
|
for city in CITIES:
|
|
results[city] = fetch_coordinates(city)
|
|
|
|
save_cache(results)
|
|
|
|
print("Saved to cache:")
|
|
print(json.dumps(results, indent=4))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|