1+ # -*- coding: utf-8 -*-
2+ '''
3+ Python 3.8 code
4+ Created on Thu Jan 4 20:41:45 2018
5+ Modified May 2022
6+
7+ @author: Heather Gorr
8+ Updated by: Emma Smith Zbarsky
9+ Copyright 2018-2022 The MathWorks, Inc.
10+
11+ Create the Openweather API-structured URL using One Call
12+ as described in the documentation
13+ https://openweathermap.org/api/one-call-api
14+ This API is licensed under CC BY-SA 4.0, as documented here:
15+ https://creativecommons.org/licenses/by-sa/4.0/
16+ '''
17+
18+ # checkcurrentweather.py
19+ import datetime
20+ import json
21+ import urllib .request
22+
23+ BASE_URL = 'http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&units={}&appid={}'
24+
25+ def get_weather (lat ,lon ,apikey ,** kwargs ):
26+ '''get current conditions in specified location, e.g.,
27+ lat = 42.2775 N, lon = 71.3468 W is Natick, MA, US
28+ get_current_weather('42.2775','-71.3468',key,units='metric')'''
29+
30+ # Initialize json_data
31+ json_data = {'Feedback' : 'nothing' }
32+
33+ # Set a default of imperial units
34+ info = {'units' :'imperial' }
35+ for key , value in kwargs .items ():
36+ info [key ] = value
37+
38+ try :
39+ url = BASE_URL .format (lat ,lon ,info ['units' ],apikey )
40+ json_data = json .loads (urllib .request .urlopen (url ).read ())
41+ except urllib .error .URLError :
42+ # if the One Call weather API doesn't work, return an error
43+ print ('We cannot access the weather service' )
44+
45+ return json_data
46+
47+
48+ def parse_current_json (json_data ):
49+ '''parse and extract json data from the current weather data'''
50+
51+ # Initialize weather_info
52+ weather_info = {'Feedback' : 'nothing' }
53+
54+ try :
55+ # select data of interest from dictionary
56+ weather_info = json_data ['main' ]
57+ # add current date and time
58+ weather_info ['local_time' ] = str (datetime .datetime .now ())
59+ weather_info ['current_time' ] = json_data ['dt' ]
60+ # make sure values are returned as floats
61+ weather_info ['temp' ] = float (weather_info ['temp' ])
62+ weather_info ['feels_like' ] = float (weather_info ['feels_like' ])
63+ weather_info ['pressure' ] = float (weather_info ['pressure' ])
64+ weather_info ['humidity' ] = float (weather_info ['humidity' ])
65+ weather_info ['wind_speed' ] = float (json_data ['wind' ]['speed' ])
66+ weather_info ['wind_deg' ] = float (json_data ['wind' ]['deg' ])
67+ weather_info ['clouds' ] = float (json_data ['clouds' ]['all' ])
68+ # Seconds shifted from UTC for location
69+ weather_info ['timezone' ] = json_data ['timezone' ]
70+ # UTC Unix time
71+ weather_info ['sunrise' ] = json_data ['sys' ]['sunrise' ]
72+ weather_info ['sunset' ] = json_data ['sys' ]['sunset' ]
73+ # String
74+ weather_info ['city_name' ] = json_data ['name' ]
75+ # Weather description as list
76+ weather_info ['weather' ] = json_data ['weather' ]
77+
78+ except KeyError as e :
79+ print ('Something went wrong while parsing current json' )
80+ raise e
81+
82+ return weather_info
0 commit comments