Skip to content

Instantly share code, notes, and snippets.

@armindocachada
Last active August 9, 2020 11:03
Show Gist options
  • Save armindocachada/e850b3600275836d2c122cbe5aabe3a1 to your computer and use it in GitHub Desktop.
Save armindocachada/e850b3600275836d2c122cbe5aabe3a1 to your computer and use it in GitHub Desktop.
def determineWeather():
"""
We call the weather API and get the weather for the next few hours.
The API itself gives way too much information. All I want to know,
what is the minimum and maximum temperature and whether is going
to rain or snow. And whether it is going to be light or heavy.
>>> determineWeather()
{'precipitation': False, 'heavyRain': False, 'heavySnow': False, 'temperatureCode': 'Hot'}
"""
import http.client
import json
conn = http.client.HTTPSConnection("api-metoffice.apiconnect.ibmcloud.com")
headers = {
'x-ibm-client-id': "<Your-Client-ID>",
'x-ibm-client-secret': "<Your-Client-Secret>",
'accept': "application/json"
}
latitude = <MY LATITUDE>
longitude = <MY LONGITUDE>
conn.request("GET",
"/metoffice/production/v0/forecasts/point/daily?excludeParameterMetadata=false&includeLocationName=true&latitude={}&longitude={}".format(
latitude, longitude), headers=headers)
res = conn.getresponse()
data = res.read()
weather = json.loads(data.decode("utf-8"))
precipitation = False
heavyRain = False
heavySnow = False
minTemperature = None
maxTemperature = None
for timeForecast in weather['features'][0]['properties']['timeSeries']:
probabilityOfPrecipitation = timeForecast['dayProbabilityOfPrecipitation']
dayProbabilityOfHeavyRain = timeForecast['dayProbabilityOfHeavyRain']
dayProbabilityOfHeavySnow = timeForecast['dayProbabilityOfHeavySnow']
if probabilityOfPrecipitation >= probabilityOfPrecipitationThreshold:
precipitation = True
if dayProbabilityOfHeavyRain >= probabilityOfHeavyRainThreshold:
heavyRain = True
if dayProbabilityOfHeavySnow >= ProbabilityOfHeavySnowThreshold:
heavySnow = True
temperature = timeForecast['dayMaxFeelsLikeTemp']
if (not minTemperature or temperature < minTemperature ):
minTemperature = temperature
if (not maxTemperature or temperature > maxTemperature ):
maxTemperature = temperature
temperatureCode = classifyTemperature(minTemperature, maxTemperature)
return {"precipitation": precipitation, "heavyRain": heavyRain, "heavySnow": heavySnow, "temperatureCode": temperatureCode }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment