Spaces:
Sleeping
Sleeping
Update data_fetcher.py
Browse files- data_fetcher.py +24 -13
data_fetcher.py
CHANGED
|
@@ -1,27 +1,38 @@
|
|
| 1 |
import requests
|
| 2 |
import pandas as pd
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
# Fetch data from NREL API
|
| 6 |
def fetch_nrel_data():
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
return response.json()
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
# Function to clean and structure data
|
| 16 |
def get_hydrogen_data():
|
|
|
|
| 17 |
data = fetch_nrel_data()
|
| 18 |
|
| 19 |
-
if "
|
| 20 |
-
return data
|
| 21 |
|
| 22 |
-
stations = data
|
| 23 |
|
| 24 |
df = pd.DataFrame(stations)
|
| 25 |
-
df = df[["station_name", "state", "status", "capacity_kg_day", "street_address", "latitude", "longitude"]]
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
import pandas as pd
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# ✅ Read API key securely from environment variables
|
| 6 |
+
NREL_API_KEY = os.getenv("NREL_API_KEY")
|
| 7 |
+
|
| 8 |
+
if not NREL_API_KEY:
|
| 9 |
+
raise ValueError("❌ ERROR: NREL API Key is missing! Set it as an environment variable.")
|
| 10 |
|
|
|
|
| 11 |
def fetch_nrel_data():
|
| 12 |
+
"""Fetch real-time hydrogen station data from NREL API."""
|
| 13 |
+
url = f"https://developer.nrel.gov/api/hydrogen/v1/stations.json?api_key={NREL_API_KEY}"
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
response = requests.get(url, timeout=10) # Timeout added for reliability
|
| 17 |
+
response.raise_for_status() # Raise error for bad responses (4xx, 5xx)
|
| 18 |
return response.json()
|
| 19 |
|
| 20 |
+
except requests.exceptions.RequestException as e:
|
| 21 |
+
print(f"⚠️ ERROR: Failed to fetch data from NREL API: {e}")
|
| 22 |
+
return None # Return None if the API call fails
|
| 23 |
|
|
|
|
| 24 |
def get_hydrogen_data():
|
| 25 |
+
"""Process hydrogen station data into a DataFrame."""
|
| 26 |
data = fetch_nrel_data()
|
| 27 |
|
| 28 |
+
if data is None or "fuel_stations" not in data:
|
| 29 |
+
return None # Return None if API data is unavailable
|
| 30 |
|
| 31 |
+
stations = data["fuel_stations"]
|
| 32 |
|
| 33 |
df = pd.DataFrame(stations)
|
|
|
|
| 34 |
|
| 35 |
+
if df.empty:
|
| 36 |
+
return None # Return None if no data is available
|
| 37 |
+
|
| 38 |
+
return df[["station_name", "state", "status", "capacity_kg_day", "street_address", "latitude", "longitude"]]
|