def test_custom_endpoint_method(self): """ Test the AerisWeather.custom_endpoint method """ try: awx = AerisWeather(app_id=app_id, client_id=client_id, client_secret=client_secret) EndpointType.custom = "forecasts" f_list = awx.custom_endpoint(location=RequestLocation( postal_code="54660")) for forecast in f_list: assert type(forecast) is CustomResponse assert len(forecast.periods) > 0 period = forecast.periods[0] # type: ForecastPeriod assert period.weather is not None except URLError as url_err: print("URL Error: " + url_err.reason) raise url_err except AerisError as aeris_err: print("AerisError: " + str(aeris_err)) raise aeris_err except Exception as ex: print(ex.args) raise ex
def url(self, endpoint_type: EndpointType, location: RequestLocation = None, action: RequestAction = None, filter_: [RequestFilter] = None, sort: RequestSort = None, params: Dict[ParameterType, str] = None, query: Dict[RequestQuery, str] = None) -> str: """ Generates the appropriate request url for a standard single API request. Generally called internally from the request method. Builds and returns a full API request URL based on the attributes passed in. Params: - endpoint_type: EndpointType - determines which Aeris API endpoint will be called - location: Optional - RequestLocation - the location for which the request is processed - action: Optional - RequestAction - the API request action option - filter_: Optional - [RequestFilter] - a list of API request filters - sort: Optional - RequestSort - the API request sort option - params: Optional - Dict[ParameterType, str] - a list of API request parameters - query: Optional - Dict[RequestQuery, str] - a list of API request quesries Returns: - url string """ url = self.url_host if endpoint_type == EndpointType.CUSTOM: url += endpoint_type.custom + "/" else: url += endpoint_type.value + "/" if action is not None: url += action.value + "/" else: url += location.location_str() url += "?client_id=" + self.client_id url += "&client_secret=" + self.client_secret if params is not None: for param, value in params.items(): url += "&" + param.value + "=" + value if sort is not None: url += "&sort=" + sort.value if filter_ is not None: if len(filter_) > 0: url += "&filter=" for filt in filter_: url += filt.value + "," out_query = self.query_str(query) if out_query is not None: url += "&query=" + out_query return url
def test_api_response(self): """ Test the code against a live response from the API """ try: awx = AerisWeather(app_id=app_id, client_id=client_id, client_secret=client_secret) forecast_list = awx.forecasts(location=RequestLocation(postal_code="54601"), action=None, filter_=[RequestFilter.FORECASTS.DAY_NIGHT], sort=None, params={ParameterType.FORECASTS.LIMIT: "1"}, query=None) for forecast in forecast_list: # type: ForecastsResponse assert forecast is not None assert forecast.loc.long < 0 assert forecast.interval is not None period = forecast.periods[0] assert type(period) is ForecastPeriod assert period.weather is not None assert period.validTime is not None except URLError as url_err: print("URL Error: " + url_err.reason) raise url_err except AerisError as aeris_err: print("AerisError: " + str(aeris_err)) raise aeris_err except Exception as ex: print(ex.args) raise ex
def test_api_response(self): """ Test the Alerts code against a live response from the API """ try: awx = AerisWeather(app_id=app_id, client_id=client_id, client_secret=client_secret) endpoint = Endpoint(endpoint_type=EndpointType.ALERTS, location=RequestLocation(postal_code="55124"), action=None, filter_=[RequestFilter.ALERTS.ALL], sort=None, params=None, query=None) alerts_list = awx.request(endpoint=endpoint) for alert in alerts_list: # type: AlertsResponse assert alert.place is not None timestamps = alert.timestamps assert type(timestamps) == AlertTimestamps assert timestamps.issued is not None includes = alert.includes assert type(includes) is AlertIncludes assert includes.wxzones is not None assert alert.active is True except URLError as url_err: print("URL Error: " + url_err.reason) raise url_err except AerisError as aeris_err: print("AerisError: " + str(aeris_err)) raise aeris_err except Exception as ex: print(ex.args) raise ex
def batch_url(self, endpoints: List[Endpoint], global_location: RequestLocation = None, global_filter_: [RequestFilter] = None, global_sort: RequestSort = None, global_params: Dict[ParameterType, str] = None, global_query: Dict[RequestQuery, str] = None) -> str: """ Generate the appropriate batch request url. The batch request also supports all of the standard endpoint parameters, such as p, limit, and query, except that when used, these batch parameters are considered global and applied to each individual request provided with the request's parameters. Note, however, that any parameters included within an individual request (within the requests parameter) will override those same global options found in the main batch request. Parameters can be passed to each individual endpoint as well but must be URL-encoded, use "%3F" for "?" and "%26" for "&". Example: https://api.aerisapi.com/batch? p=truckee,nv&client_id=###########&client_secret=######################## &requests= /places/54660, /advisories%3Flimit=1%26radius=10mi, /observations%3Fp=54601 Params: - endpoints: List[Endpoint] - a list of Endpoint objects, one for each request in the batch request - global_location: RequestLocation - a RequestLocation object that will be applied to each request, unless the request has a local RequestLocation - global_filter_: [RequestFilter] - a list of RequestFilters that will be applied to each request, unless the request has a local RequestFilter - global_sort: RequestSort - a RequestSort object that will be applied to each request, unless the request has a local RequestSort - global_params: Dict[ParameterType, str] - a dictionary of parameters that will be applied to each request, unless the request has a local parameter dict - global_query: Dict[RequestQuery, str] - a dictionary of queries that will be applied to each request, unless the request has a local query dict Returns: - url string for the batch_request """ url = self.url_host + "batch?client_id=" + self.client_id + "&client_secret=" + self.client_secret # add the global request parameters - these apply to all endpoints in the batch request if global_location is not None: url += "&p=" + global_location.location_str() if global_filter_ is not None: if len(global_filter_) > 0: url += "&filter=" for filt in global_filter_: url += filt.value + "," if global_params is not None: for param, value in global_params.items(): url += "&" + param.value + "=" + value if global_sort is not None: url += "&sort=" + global_sort.value out_query = self.query_str(global_query) if out_query is not None: url += "&query=" + out_query # add the requests section url += "&requests=" # add the specifc endpoint requests and their parameters for endpoint in endpoints: has_param = False url += "/" + endpoint.endpoint_type.value if endpoint.action is not None: url += "/" + endpoint.action.value if endpoint.location is not None: url += "%3Fp=" + endpoint.location.location_str() has_param = True if endpoint.filter_ is not None and len(endpoint.filter_) > 0: if has_param: url += "%26filter=" else: url += "%3Ffilter=" for filt in endpoint.filter_: url += filt.value + "," has_param = True if endpoint.params is not None: for param, value in endpoint.params.items(): if has_param: url += "%26" else: url += "%3F" url += param.value + "=" + value + "," has_param = True if endpoint.sort is not None: if has_param: url += "%26sort=" else: url += "%3Fsort=" url += endpoint.sort.value has_param = True out_query = self.query_str(endpoint.query) if out_query is not None: if has_param: url += "%26query=" else: url += "%3Fquery=" url += out_query # has_param = True # add a trailing comma in case there are more endpoints if not url.endswith(","): url += "," # strip unused trailing commas while url.endswith(","): url = url[:-1] return url
""" Provided to show example use cases for the AerisWeather Python library. """ from aerisweather.aerisweather import AerisWeather from aerisweather.requests.ParameterType import ParameterType from aerisweather.requests.RequestLocation import RequestLocation from aerisweather.requests.RequestAction import RequestAction from aerisweather.requests.RequestFilter import RequestFilter from keys import client_id, client_secret, app_id # Set the AerisWeather client id and secret. aeris = AerisWeather(client_id=client_id, client_secret=client_secret, app_id=app_id) # Create a RequestLocation object to be used with any endpoint requests. loc = RequestLocation(city="tomah", state="wi") """ Observations Request Example 1 """ # Create a simple observations request with no options. We will receive a list of ObservationsResponse objects obs_list = aeris.observations(location=loc) for obs in obs_list: # get the AerisPlace responses object place = obs.place # get the observations data object ob = obs.ob # get some observations data tempF = ob.tempF weather = ob.weather
def test_api_response(self): """ Test against a live response from the API """ try: awx = AerisWeather(app_id=app_id, client_id=client_id, client_secret=client_secret) # Valid endpoint, not in our Endpoint Enum - run this to test a beta or pre-release endpoint EndpointType.custom = "stormreports" endpt = Endpoint(EndpointType.CUSTOM, location=RequestLocation(postal_code="54660")) try: resp_list = awx.request(endpt) response = resp_list[0] assert type(response) is CustomResponse except AerisError as ae_ex: logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(' stormreports endpoint test ') logger.error(str(ae_ex)) except Exception as ex: logging.basicConfig(level=logging.ERROR) logger = logging.getLogger(' stormreports endpoint test ') logger.error(str(ex)) # You can also use the custom endpoint type to request data from a known valid endpoint, for cases # where new API data fields have not yet been added to an endpoint's response class. EndpointType.custom = "forecasts" f_list = awx.request( endpoint=Endpoint(endpoint_type=EndpointType.CUSTOM, location=RequestLocation( postal_code="54660"))) forecast = f_list[0] assert type(forecast) is CustomResponse assert len(forecast.periods) > 0 period = forecast.periods[0] # type: ForecastPeriod assert period.weather is not None # Another example, with lots of nested lists, etc. # rivers/gauges EndpointType.custom = "rivers/gauges" rg_list = awx.request( endpoint=Endpoint(endpoint_type=EndpointType.CUSTOM, location=RequestLocation( postal_code="57101"))) rg = rg_list[0] assert type(rg) is CustomResponse profile = rg.profile # type: AerisProfileRiversGauges crests = profile.crests # type: RiversCrests recent = crests.recent # type: [RiversCrestsRecent] assert len(recent) > 0 assert recent[0].heightFT is not None # Unknown and invalid endpoint EndpointType.custom = "bogus/endpoint" invalid_list = awx.request( endpoint=Endpoint(endpoint_type=EndpointType.CUSTOM, location=RequestLocation( postal_code="57101"))) # the results of this call will be a thrown AerisError exception. except URLError as url_err: print("URL Error: " + url_err.reason) raise url_err except AerisError as aeris_err: assert aeris_err.code == "invalid_request" print("AerisError: " + "Level: " + aeris_err.level.value + " - " + str(aeris_err)) # raise aeris_err except Exception as ex: print(ex.args) raise ex
def test_api_batch_response(self): """ Test against a batch response from the API """ try: awx = AerisWeather(app_id=app_id, client_id=client_id, client_secret=client_secret) endpoint = Endpoint(endpoint_type=EndpointType.OBSERVATIONS, location=None, action=None, filter_=None, sort=None, params={ParameterType.OBSERVATIONS.LIMIT: "3"}) endpoint2 = Endpoint(endpoint_type=EndpointType.FORECASTS, params={ParameterType.FORECASTS.LIMIT: "3"}) endpoint3 = Endpoint(endpoint_type=EndpointType.OBSERVATIONS_SUMMARY) endpoints = [endpoint, endpoint2, endpoint3] response_list = awx.batch_request(endpoints=endpoints, global_location=RequestLocation(postal_code="54660")) for resp in response_list: if type(resp) is ObservationsResponse: # Observations obs = resp assert type(obs) is ObservationsResponse assert obs.id is not None loc = obs.loc assert loc is not None assert type(loc) is AerisLocation assert obs.loc.lat > 43 place = obs.place assert place is not None # assert place.name == "la crosse" assert place.state == "wi" profile = obs.profile assert profile is not None assert profile.elevFT > 600 relative_to = obs.relativeTo assert relative_to.long < -80 assert obs.obTimestamp.__class__ is int elif type(resp) is ForecastsResponse: # Forecasts forecast = resp assert type(forecast) is ForecastsResponse loc = forecast.loc assert loc is not None assert type(loc) is AerisLocation assert forecast.loc.lat > 43 assert forecast.interval is not None period = forecast.periods[0] assert type(period) is ForecastPeriod assert period.weather is not None assert period.validTime is not None elif type(resp) is ObservationsSummaryResponse: # ObservationsSummary obs_sum = resp assert type(obs_sum) is ObservationsSummaryResponse assert obs_sum.id is not None loc = obs_sum.loc assert loc is not None assert type(loc) is AerisLocation assert obs_sum.loc.lat > 43 place = obs_sum.place assert place is not None # assert place.name == "la crosse" assert place.state == "wi" periods = obs_sum.periods assert periods is not None temp = periods[0].temp assert type(temp) is ObservationsSummaryTemp assert temp.avgF > -10 profile = obs_sum.profile assert profile is not None assert profile.elevFT > 600 except URLError as url_err: print("URL Error: " + url_err.reason) raise url_err except AerisError as aeris_err: print("AerisError: " + str(aeris_err)) raise aeris_err except Exception as ex: print(ex.args) raise ex
from aerisweather.aerisweather import AerisWeather from aerisweather.requests.ParameterType import ParameterType from aerisweather.requests.RequestLocation import RequestLocation from aerisweather.requests.RequestAction import RequestAction from aerisweather.requests.RequestFilter import RequestFilter # from keys import client_id, client_secret, app_id aeris = AerisWeather(client_id='j7lOmijllhziSzpk0x6bO', client_secret='a0ZhdOcImgWhhFDEb5X8V64k4WH67lKyGtWTDZe8') print(aeris) loc = RequestLocation(postal_code='94086') obs_list = aeris.observations(location=loc) print(obs_list) # forecast_lst = aeris.forecasts(location=loc, # params={ParameterType.FORECASTS.FIELDS: 'periods.isDay, periods.maxTempF, periods.minTempF, periods.weather'}) # print("********** \n{}".format(forecast_lst)) # for forecast in forecast_lst: # if forecast.periods[0].isDay: # day = forecast.periods[0] # night = forecast.periods[1] # else: # day = forecast.periods[1] # night = forecast.periods[0]