def get_session() -> CachedSession: """Make a cached session.""" path = settings.STATE_PATH.joinpath("http").as_posix() session = CachedSession(cache_name=path, expire_after=settings.CACHE_EXPIRE) session.headers.update(HEADERS) # weird monkey-patch: default timeout for requests sessions session.request = functools.partial(session.request, timeout=settings.HTTP_TIMEOUT) return session
def output_weather_data(zip_code, metric): if metric: temp_unit = "C" rain_unit = "mm" wind_unit = "km/h" else: temp_unit = "F" rain_unit = "in" wind_unit = "mph" weather_data_dict = dict() accuweatherSession = CachedSession("accuweather_cache", old_data_on_error=True) location_session = accuweatherSession.request( "GET", f"{api_url_prefix}/locations/v1/postalcodes/US/search?apikey={api_key}&q={zip_code}&language=en-us", expire_after=-1, ) print("location data from cache:", location_session.from_cache) location_json = json.loads(location_session.text) locationKeyValue = location_json[0]["Key"] forecast_session = accuweatherSession.request( "GET", f"{api_url_prefix}/forecasts/v1/daily/5day/{locationKeyValue}?apikey={api_key}&language=en-us&details=true&metric={str(metric).lower()}", expire_after=3600, ) print("forecast data from cache:", forecast_session.from_cache) forecast_json = json.loads(forecast_session.text) for forecast in forecast_json["DailyForecasts"]: TempObj = forecast["Temperature"] HeatIndxObj = forecast["RealFeelTemperature"] WindObj = forecast["Day"]["Wind"] WindDegrees = WindObj["Direction"]["Degrees"] WindGObj = forecast["Day"]["WindGust"] WindGDegrees = WindGObj["Direction"]["Degrees"] precipitation_length = timedelta( hours=forecast["Day"]["HoursOfPrecipitation"]).total_seconds() hours, remainder = divmod(precipitation_length, 3600) minutes = divmod(remainder, 60)[0] summary = f"{icons[forecast['Day']['Icon']]} {TempObj['Maximum']['Value']:.0f}° | {TempObj['Minimum']['Value']:.0f}°, {forecast['Day']['IconPhrase']}" if forecast["Day"]["HasPrecipitation"]: summary += f" ({forecast['Day']['Rain']['Value']} {rain_unit})" description = f"Temperature unit: {TempObj['Minimum']['Value']:.0f}°{temp_unit} … {TempObj['Maximum']['Value']:.0f}°{temp_unit}\n" description += f"Heat index: {HeatIndxObj['Minimum']['Value']:.0f}°{temp_unit} … {HeatIndxObj['Maximum']['Value']:.0f}°{temp_unit}\n\n" description += f"Precipitation: {forecast['Day']['Rain']['Value']} {rain_unit}\n" description += f"Length of precipitation: {hours:.0f} h" if minutes > 0: description += f" {minutes:.0f} m" description += f"\nChance of rain: {forecast['Day']['PrecipitationProbability']:.0f}%\n" description += f"Cloud cover: {forecast['Day']['CloudCover']:.0f}%\n\n" description += f"Wind: {WindObj['Speed']['Value']} {wind_unit} {winds[WindDegrees]} ({WindDegrees}°)\n" description += ( f"Wind gust: {WindGObj['Speed']['Value']} {wind_unit} {winds[WindGDegrees]} ({WindGDegrees}°)\n\n" ) description += f"Additional information\n{forecast['Link']}" weather_data_dict[forecast["EpochDate"]] = [ summary, description, forecast["Link"] ] return weather_data_dict
def request(self,*args,**kwargs) : kwargs.update(self._init["kwargs"]) return CachedSession.request(self,*args,**kwargs)