-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfetch_realtime_weather.py
42 lines (33 loc) · 1.24 KB
/
fetch_realtime_weather.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import requests
import json
import os
from datetime import datetime
def fetch_weather(api_key, city_code):
url = f"https://restapi.amap.com/v3/weather/weatherInfo?key={api_key}&city={city_code}"
response = requests.get(url)
return response.json()
def extract_realtime_weather(weather_data):
live_weather = weather_data["lives"][0]
return {
"reporttime": live_weather["reporttime"],
"weather": live_weather["weather"],
"temperature": live_weather["temperature"]
}
def main():
api_key = os.getenv("API_KEY")
city_code = "340104"
weather_data = fetch_weather(api_key, city_code)
if "lives" in weather_data and len(weather_data["lives"]) > 0:
realtime_weather = extract_realtime_weather(weather_data)
if os.path.exists("realtime_weather.json"):
with open("realtime_weather.json", "r") as file:
data = json.load(file)
else:
data = {"time": []}
data["time"].append(realtime_weather)
with open("realtime_weather.json", "w") as file:
json.dump(data, file, indent=4, ensure_ascii=False)
else:
print("No live weather data found.")
if __name__ == "__main__":
main()