- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathcurrent_weather.py
50 lines (43 loc) · 1.74 KB
/
current_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
43
44
45
46
47
48
49
50
importrequests
# Put your API key(s) here
OPENWEATHERMAP_API_KEY=""
WEATHERSTACK_API_KEY=""
# Define the URL for the APIs with placeholders
OPENWEATHERMAP_URL_BASE="https://api.openweathermap.org/data/2.5/weather"
WEATHERSTACK_URL_BASE="http://api.weatherstack.com/current"
defcurrent_weather(location: str) ->list[dict]:
"""
>>> current_weather("location")
Traceback (most recent call last):
...
ValueError: No API keys provided or no valid data returned.
"""
weather_data= []
ifOPENWEATHERMAP_API_KEY:
params_openweathermap= {"q": location, "appid": OPENWEATHERMAP_API_KEY}
response_openweathermap=requests.get(
OPENWEATHERMAP_URL_BASE, params=params_openweathermap, timeout=10
)
weather_data.append({"OpenWeatherMap": response_openweathermap.json()})
ifWEATHERSTACK_API_KEY:
params_weatherstack= {"query": location, "access_key": WEATHERSTACK_API_KEY}
response_weatherstack=requests.get(
WEATHERSTACK_URL_BASE, params=params_weatherstack, timeout=10
)
weather_data.append({"Weatherstack": response_weatherstack.json()})
ifnotweather_data:
raiseValueError("No API keys provided or no valid data returned.")
returnweather_data
if__name__=="__main__":
frompprintimportpprint
location="to be determined..."
whilelocation:
location=input("Enter a location (city name or latitude,longitude): ").strip()
iflocation:
try:
weather_data=current_weather(location)
forforecastinweather_data:
pprint(forecast)
exceptValueErrorase:
print(repr(e))
location=""