1
+ import jwt
2
+ import time # https://www.systutorials.com/how-to-get-the-epoch-timestamp-in-python/
3
+ import requests
4
+
5
+ def create_key (signature_alg , key_id , team_id , service_id , iat , key_path ):
6
+ """This function takes the required information as arguments and returns an encoded key to pass as a parameter for the Apple WeatherKit API."""
7
+ with open (key_path , 'rb' ) as f :
8
+ key = f .read ()
9
+
10
+ header = {
11
+ "kid" : key_id ,
12
+ "id" : f"{ team_id } .{ service_id } " ,
13
+ }
14
+
15
+ payload = {
16
+ "iss" : team_id ,
17
+ "iat" : iat ,
18
+ "exp" : iat + 3600 ,
19
+ "sub" : service_id
20
+ }
21
+
22
+ s = jwt .encode (payload , key , algorithm = signature_alg , headers = header )
23
+
24
+ return s
25
+
26
+ 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."""
28
+ response = requests .get (f"https://weatherkit.apple.com/api/v1/weather/{ language } /{ latitude } /{ longitude } " , headers = {
29
+ 'Authorization' : f'Bearer { web_token } ' ,
30
+ 'Accept' : 'application/json'
31
+ },
32
+ params = {
33
+ 'timezone' : timezone ,
34
+ 'dataSets' : 'currentWeather'
35
+ })
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
46
+
47
+ def main ():
48
+ web_token = create_key ("ES256" ,
49
+ "74B4NT7KNA" ,
50
+ "AJAJ8VTADD" ,
51
+ "com.homedashboard.test" ,
52
+ int (time .time ()),
53
+ "C:/Users/zacha/OneDrive/Coding/Keys/Home_Dashboard/WeatherKit/AuthKey_74B4NT7KNA.p8"
54
+ )
55
+ print (web_token )
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).' )
60
+
61
+ main ()
0 commit comments