Skip to content

Commit

Permalink
New API gatway. Requires new API key.
Browse files Browse the repository at this point in the history
  • Loading branch information
coinish committed Apr 23, 2024
1 parent 325574c commit d966a09
Show file tree
Hide file tree
Showing 3 changed files with 144 additions and 56 deletions.
60 changes: 5 additions & 55 deletions met_weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
# support: https://groups.google.com/g/metoffice-datapoint

import api
import ss_download
# from https://raw.githubusercontent.com/MetOffice/weather_datahub_utilities/main/site_specific_download/ss_download.py
# i replaced print(req.text)
# with return (req.json())
import datetime
from dateutil import tz

Expand Down Expand Up @@ -94,60 +98,6 @@ def get_next_sunrise_or_sunset_msg(now, lon, lat, local_timezone_name):



def get_forecast(lon, lat):

import http.client
import json
import time

max_retries=4
retry_delay_seconds=180

#request
conn = http.client.HTTPSConnection("api-metoffice.apiconnect.ibmcloud.com")

headers = {
'X-IBM-Client-Id': api.clientId,
'X-IBM-Client-Secret': api.clientSecret,
'accept': "application/json"
}

for retry in range(max_retries):
try:
conn.request("GET", f"/v0/forecasts/point/hourly?excludeParameterMetadata=REPLACE_THIS_VALUE&includeLocationName=true&latitude={lat}&longitude={lon}", headers=headers)
res = conn.getresponse()
data = res.read()
return json.loads(data)

except http.client.RemoteDisconnected:
time.sleep(retry_delay_seconds)
else:
# If all retries fail, raise an error or handle it accordingly
raise Exception(f"Failed to establish a connection after {max_retries} retries.")




def get_daily_forecast(lon, lat):

import http.client
import json

#request
conn = http.client.HTTPSConnection("api-metoffice.apiconnect.ibmcloud.com")

headers = {
'X-IBM-Client-Id': api.clientId,
'X-IBM-Client-Secret': api.clientSecret,
'accept': "application/json"
}

conn.request("GET", f"/v0/forecasts/point/daily?excludeParameterMetadata=REPLACE_THIS_VALUE&includeLocationName=REPLACE_THIS_VALUE&latitude={lat}&longitude={lon}", headers=headers)
res = conn.getresponse()
data = res.read()

return json.loads(data)



# met office api significant weather codes
Expand Down Expand Up @@ -244,7 +194,7 @@ def make_default_icon_dirs():
print (get_next_sunrise_or_sunset_msg(now, api.lon, api.lat, local_timezone_name))

# hourly forecast
forecast= get_forecast(api.lon, api.lat)
forecast = ss_download.retrieve_forecast(ss_download.base_url, "hourly", {"apikey": api.key}, api.lat, api.lon, "FALSE", "TRUE")
#print (forecast)

#daily= get_daily_forecast(lon, lat)
Expand Down
133 changes: 133 additions & 0 deletions ss_download.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
# 2023 (C) Crown Copyright, Met Office. All rights reserved.
#
# This file is part of Weather DataHub and is released under the
# BSD 3-Clause license.
# See LICENSE in the root of the repository for full licensing details.
# (c) Met Office 2023

import requests
import argparse
import time
import sys
import logging as log

log.basicConfig(filename='ss_download.log', filemode='w', format='%(asctime)s - %(levelname)s - %(message)s')

base_url = "https://data.hub.api.metoffice.gov.uk/sitespecific/v0/point/"

def retrieve_forecast(baseUrl, timesteps, requestHeaders, latitude, longitude, excludeMetadata, includeLocation):

url = baseUrl + timesteps

headers = {'accept': "application/json"}
headers.update(requestHeaders)
params = {
'excludeParameterMetadata' : excludeMetadata,
'includeLocationName' : includeLocation,
'latitude' : latitude,
'longitude' : longitude
}

success = False
retries = 5

while not success and retries >0:
try:
req = requests.get(url, headers=headers, params=params)
success = True
except Exception as e:
log.warning("Exception occurred", exc_info=True)
retries -= 1
time.sleep(10)
if retries == 0:
log.error("Retries exceeded", exc_info=True)
sys.exit()

req.encoding = 'utf-8'

#print(req.text)
return (req.json())


if __name__ == "__main__":

parser = argparse.ArgumentParser(
description="Retrieve the site-specific forecast for a single location"
)
parser.add_argument(
"-t",
"--timesteps",
action="store",
dest="timesteps",
default="hourly",
help="The frequency of the timesteps provided in the forecast. The options are hourly, three-hourly or daily",
)
parser.add_argument(
"-m",
"--metadata",
action="store",
dest="excludeMetadata",
default="FALSE",
help="Provide a boolean value for whether parameter metadata should be excluded."
)
parser.add_argument(
"-n",
"--name",
action="store",
dest="includeLocation",
default="TRUE",
help="Provide a boolean value for whether the location name should be included."
)
parser.add_argument(
"-y",
"--latitude",
action="store",
dest="latitude",
default="",
help="Provide the latitude of the location you wish to retrieve the forecast for."
)
parser.add_argument(
"-x",
"--longitude",
action="store",
dest="longitude",
default="",
help="Provide the longitude of the location you wish to retrieve the forecast for."
)
parser.add_argument(
"-k",
"--apikey",
action="store",
dest="apikey",
default="",
help="REQUIRED: Your WDH API Credentials."
)

args = parser.parse_args()

timesteps = args.timesteps
includeLocation = args.includeLocation
excludeMetadata = args.excludeMetadata
latitude = args.latitude
longitude = args.longitude
apikey = args.apikey

# Client API key must be supplied
if apikey == "":
print("ERROR: API credentials must be supplied.")
sys.exit()
else:
requestHeaders = {"apikey": apikey}

if latitude == "" or longitude == "":
print("ERROR: Latitude and longitude must be supplied")
sys.exit()

if timesteps != "hourly" and timesteps != "three-hourly" and timesteps != "daily":
print("ERROR: The available frequencies for timesteps are hourly, three-hourly or daily.")
sys.exit()

print (retrieve_forecast(base_url, timesteps, requestHeaders, latitude, longitude, excludeMetadata, includeLocation))



7 changes: 6 additions & 1 deletion weatherWHAT.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@


import argparse
import ss_download
# from https://raw.githubusercontent.com/MetOffice/weather_datahub_utilities/main/site_specific_download/ss_download.py
# i replaced print(req.text)
# with return (req.json())

try:
import api
Expand Down Expand Up @@ -98,7 +102,8 @@ def display_weather(
else:
# get current forecast
now, local_timezone_name, local_now= met_weather.get_now(lon, lat)
forecast= met_weather.get_forecast(lon, lat)
forecast = ss_download.retrieve_forecast(ss_download.base_url, "hourly", {"apikey": api.key}, api.lat, api.lon, "FALSE", "TRUE")


if saveforecast:
#save weather and reload it to check
Expand Down

0 comments on commit d966a09

Please sign in to comment.