def get_today(self): client = ApixuClient(self.api_key) current = client.getForecastWeather(q=self.city, days=1) high = current['forecast']['forecastday'][0]['day']['maxtemp_f'] low = current['forecast']['forecastday'][0]['day']['mintemp_f'] average = current['forecast']['forecastday'][0]['day']['avgtemp_f'] description = current['forecast']['forecastday'][0]['day'][ 'condition']['text'] return high, low, average, description
def getApixu(ApiKey): # create the Apixu client obj & query current & 7 forecast weather data try: client = ApixuClient(ApiKey) # these weather are in a dict form [json] currentWeather = client.getCurrentWeather(q = "Harare") # get current weather for Hre forecastWeather = client.getForecastWeather(q = "Harare", days = 7) # get weather forecast for Hre return True, currentWeather, forecastWeather except ApixuException as e: return False, "[!] Error querying data {}".format(e.message)
'name': 'London', 'region': 'City Of London, Greater London', 'tz_id': 'Europe/London' } } """ print current['current']['wind_degree'] # show wind degree print current['current']['temp_c'] # show temprature in celsius print current['location']['country'] # name of country print current['location']['lat'] # latitude value print current['location']['lat'] # longitude value ########################### # forecast weather ########################### forecast = client.getForecastWeather(q='Madrid', days=10) # "forecast" is a dict with a structure like this: ''' { 'current': { ... }, 'location': { ... }, 'forecast': { 'forecastday': [{ 'astro': { 'moonrise': '06:07 PM', 'moonset': '03:33 AM', 'sunrise': '05:29 AM',
def on_get(self, req, resp): #Alphabet list to check against client's state entry for proper weather API routing clientlog = open('/Weather API Conflict/logs/accesslog.txt', "a") alphabet = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z' ] alphabetlow = [ letter.lower() for letter in alphabet ] #using .lower method in case client enter state with lowercase letter print(alphabet) print(alphabetlow) city = req.get_param('city') zipcode = req.get_param('zip') state = req.get_param('state') print('Client requesting weather information for ' + city + ', ' + state + ' with zipcode of ' + zipcode) statebegins = state[0:1] if (re.match("^[A-Za-z ]+$", state) and re.match("^[A-Za-z ]+$", city) and re.match("^[0-9]+$", zipcode)): print('All characters are letters') try: if ( statebegins in alphabet[0:13] ): #send client request to openweather API if state begins with A - M clientlog.write( str(datetime.now()) + ': Client requesting weather information for ' + city + ', ' + state + ' with zipcode of ' + zipcode) print( state + ' weather information must be requested from Open Weather Api' ) logger.info( 'Starting Weather forecast request to OpenWeather API') resp.status = falcon.HTTP_200 owapikey = "0c9597524a3f445d77b02ccda4e6b577" request_url = "https://api.openweathermap.org/data/2.5/weather" request_param = {'zip': zipcode, 'appid': owapikey} request_header = {} request_response = requests.get(url=request_url, params=request_param, headers=request_header) request_url2 = "https://api.openweathermap.org/data/2.5/forecast" request_param2 = {'zip': zipcode, 'appid': owapikey} request_header2 = {} request_response2 = requests.get(url=request_url2, params=request_param2, headers=request_header2) weatherinfo = request_response.json() wi = weatherinfo weatherinfo2 = request_response2.json() wi2 = weatherinfo2 print(request_url) #construct weather information response from OpenWeather API tobody = ('Location: ' + wi['name'] + '\n' + 'Current Temperature: ' + str(wi['main']['temp']) + '\n' + 'Tom. High: ' + str(wi2['list'][0]['main']['temp_max']) + '\n' + 'Tom. Low: ' + str(wi2['list'][0]['main']['temp_min']) + '\n' + 'Current Weather Conditions: ' + wi['weather'][0]['description'] + '\n' + 'Tom. Weather Conditions: ' + wi2['list'][0]['weather'][0]['description'] + '\n' + 'Sunrise: ' + str(wi['sys']['sunrise']) + '\n' + 'Sunset: ' + str(wi['sys']['sunset'])) jsonbodyow = { 'Location': wi['name'], 'Current Temperature': str(wi['main']['temp']), 'Tom. High': str(wi2['list'][0]['main']['temp_max']), 'Tom. Low': str(wi2['list'][0]['main']['temp_min']), 'Current Weather Conditions': wi['weather'][0]['description'], 'Tom. Weather Conditions': wi2['list'][0]['weather'][0]['description'], 'Sunrise': str(wi['sys']['sunrise']), 'Sunset': str(wi['sys']['sunset']) } #Print nonjsonformatted weather info to terminal #print(tobody) owjsonbody = json.dumps(jsonbodyow) jsonbodyload = json.loads(owjsonbody) print(owjsonbody) #display weather information in client body nonjsonformatted #resp.body = (tobody) #JSON Formatted body response resp.append_header('API', 'Open Weather API') resp.body = owjsonbody elif ( statebegins in alphabet[13:25] ): #send client request to apixu API if state begins with N - Z print( state + ' weather information must be requested from APIXU Api' ) logger.info( 'Starting Weather forecast request to APIXU API') resp.status = falcon.HTTP_200 xuapikey = "b8f9f07b62c7415fa8862117183108" client = ApixuClient(xuapikey) current = client.getCurrentWeather(q=zipcode) forecast = client.getForecastWeather(q=zipcode, days=2) #construct weather information response from APIXU tobodyxu = ( 'Location: ' + current['location']['name'] + '\n' + 'Current Temperature: ' + str(current['current']['temp_c']) + '\n' + 'Tom. High: ' + str(forecast['forecast']['forecastday'] [1]['day']['maxtemp_c']) + '\n' + 'Tom. Low: ' + str(forecast['forecast']['forecastday'] [1]['day']['mintemp_c']) + '\n' + 'Current Weather Conditions: ' + current['current']['condition']['text'] + '\n' + 'Tom. Weather Conditions: ' + str(forecast['forecast']['forecastday'][1]['day'] ['condition']['text']) + '\n' + 'Sunrise: ' + forecast['forecast']['forecastday'][0]['astro'] ['sunrise'] + '\n' + 'Sunset: ' + forecast['forecast'] ['forecastday'][0]['astro']['sunset']) #Weather information formatted for JSON conversion jsonbodyxu = { ' Location': current['location']['name'], 'Current Temperature': str(current['current']['temp_c']), 'Tom. High': str(forecast['forecast']['forecastday'][1]['day'] ['maxtemp_c']), 'Tom. Low': str(forecast['forecast']['forecastday'][1]['day'] ['mintemp_c']), 'Current Weather Conditions': current['current']['condition']['text'], 'Tom. Weather Conditions': str(forecast['forecast']['forecastday'][1]['day'] ['condition']['text']), 'Sunrise': forecast['forecast']['forecastday'][0]['astro'] ['sunrise'], 'Sunset': forecast['forecast']['forecastday'][0]['astro'] ['sunset'] } #Print nonjsonformatted weather info to terminal #print(tobodyxu) jsonbody = json.dumps(jsonbodyxu) jsonbodyload = json.loads(jsonbody) print(jsonbody) #display weather information in client body nonjsonformatted #resp.body = (tobodyxu) #Json Formatted Body Response resp.body = (jsonbody) else: #respond with error if client enters invalid state i.e. first character is not a letter print('Error in parameters issued by client') resp.status = falcon.HTTP_406 resp.body = 'You have entered an invalid State parameter.' except Exception: logger.error('Something major has gone wrong', exc_info=True) else: resp.status = falcon.HTTP_406 logger.error('Client entered invalid parameters', exc_info=True) #resp.body = 'Your input contains invalid characters.' raise falcon.HTTPError('Bad request', 'Your input contains invalid characters.')
from forecast_class import Forecast from geopy.geocoders import Nominatim from apixu.client import ApixuClient, ApixuException api_key = "7a9f9b37ebe0fddb2aec86405a972ff6" geolocator = Nominatim() location1 = geolocator.geocode("Lviv") lat = location1.latitude lng = location1.longitude time = datetime.datetime.now() forecast1 = forecastio.load_forecast(api_key, lat, lng, time=time).json api_key1 = "79c89a7b53c24ffb8de111947180304" client = ApixuClient(api_key1) forecast2 = client.getForecastWeather(q='Lviv', days=1) print(str(forecast1)) print(str(forecast2)) a = Forecast() forecastio = ['daily', 'data', 0] apixu = ['forecast', 'forecastday', 0, 'day'] a.add(forecast1, forecastio + ['temperatureMin'], "min_temp") a.add(forecast1, forecastio + ['temperatureMax'], "max_temp") a.add(forecast2, apixu + ['maxtemp_c'], 'max_temp') a.add(forecast2, apixu + ['mintemp_c'], 'min_temp') print(a) a.close() print(a)
def test_getForecastWeather_invalid_api_key(self): client = ApixuClient('INVALID_KEY') with self.assertRaises(ApixuException) as cm: client.getForecastWeather() self.assertEqual(cm.exception.code, 2006)
def test_getForecastWeather_no_api_key(self): client = ApixuClient() with self.assertRaises(ApixuException) as cm: client.getForecastWeather() self.assertEqual(cm.exception.code, 1002)