Skip to content

Commit 889a1ed

Browse files
Completed the get weather API call and added a temp converter.
1 parent 28528bc commit 889a1ed

File tree

1 file changed

+17
-8
lines changed

1 file changed

+17
-8
lines changed

code/zach/mini-capstone.py

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
1-
from authlib.jose import jwt # https://docs.authlib.org/en/latest/jose/index.html
1+
import jwt
22
import time # https://www.systutorials.com/how-to-get-the-epoch-timestamp-in-python/
33
import requests
44

5-
65
def create_key(signature_alg, key_id, team_id, service_id, iat, key_path):
76
"""This function takes the required information as arguments and returns an encoded key to pass as a parameter for the Apple WeatherKit API."""
87
with open(key_path, 'rb') as f:
98
key = f.read()
109

1110
header = {
12-
"alg": signature_alg,
1311
"kid": key_id,
1412
"id": f"{team_id}.{service_id}",
1513
}
@@ -21,11 +19,12 @@ def create_key(signature_alg, key_id, team_id, service_id, iat, key_path):
2119
"sub": service_id
2220
}
2321

24-
s = jwt.encode(header, payload, key)
22+
s = jwt.encode(payload, key, algorithm=signature_alg, headers=header)
2523

2624
return s
2725

2826
def get_weather(language, latitude, longitude, web_token, timezone):
27+
"""This function takes the location data, web token from create_key(), and the timezone to return the current weather condition and temperature from the Apple WeatherKit API."""
2928
response = requests.get(f"https://weatherkit.apple.com/api/v1/weather/{language}/{latitude}/{longitude}", headers = {
3029
'Authorization': f'Bearer {web_token}',
3130
'Accept': 'application/json'
@@ -34,9 +33,16 @@ def get_weather(language, latitude, longitude, web_token, timezone):
3433
'timezone': timezone,
3534
'dataSets': 'currentWeather'
3635
})
37-
print(response)
38-
#current_weather = response.json()
39-
#return current_weather
36+
37+
weather = response.json()
38+
39+
current_condition = weather['currentWeather']['conditionCode']
40+
current_temp = weather['currentWeather']['temperature']
41+
42+
return current_condition, current_temp
43+
44+
def temp_converter(temp_celsius):
45+
return temp_celsius * 1.8 + 32
4046

4147
def main():
4248
web_token = create_key("ES256",
@@ -47,6 +53,9 @@ def main():
4753
"C:/Users/zacha/OneDrive/Coding/Keys/Home_Dashboard/WeatherKit/AuthKey_74B4NT7KNA.p8"
4854
)
4955

50-
get_weather('en', 38.933868, -77.177261, web_token, 'America/New_York')
56+
current_condition, current_temp = get_weather('en', 38.933868, -77.177261, web_token, 'America/New_York')
57+
temp_fahrenheit = temp_converter(current_temp)
58+
59+
print(f'It is currently {current_condition} and {round(temp_fahrenheit, 2)} degrees Fahrenheit ({current_temp} degrees Celsius).')
5160

5261
main()

0 commit comments

Comments
 (0)