Skip to content
Snippets Groups Projects
Commit 14c96865 authored by Sara Savanovic Djordjevic's avatar Sara Savanovic Djordjevic
Browse files

fix: get_weather YR req and JSON conversion

parent f05f8ce3
No related branches found
No related tags found
No related merge requests found
No preview for this file type
...@@ -7,52 +7,82 @@ import json ...@@ -7,52 +7,82 @@ import json
# get_weather retrieves weather data for a list of coordinate pairs # get_weather retrieves weather data for a list of coordinate pairs
def get_weather(self): def get_weather(self):
# Extract coordinates form json data in POST request # Extract coordinates form json data in POST request
content_length = int(self.headers['Content-Length']) try:
post_data = self.rfile.read(content_length) content_length = int(self.headers['Content-Length'])
request_data = json.loads(post_data.decode('utf-8')) post_data = self.rfile.read(content_length)
coordinates = request_data['coords'] request_data = json.loads(post_data.decode('utf-8'))
coordinates = request_data['coords']
except KeyError: # Coords key not found in request
self.send_response(400)
self.send_header("Content-type", "application/json")
self.end_headers()
response_message = {"error": "No 'coords' provided in request body"}
self.wfile.write(json.dumps(response_message).encode('utf-8'))
return
except Exception as e:
self.send_response(500)
self.send_header("Content-type", "application/json")
self.end_headers()
response_message = {"error": "Failed to parse request body"}
self.wfile.write(json.dumps(response_message).encode('utf-8'))
return
# Form timestamp string with correct format
# Form timestamp string with correct format # Form timestamp string with correct format
current_time = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ") current_time = datetime.datetime.utcnow()
current_time = current_time.replace(minute=0, second=0)
current_time_str = current_time.strftime("%Y-%m-%dT%H:%M:%SZ")
# Set User-Agent header
user_agent = "IceApp sarasdj@stud.ntnu.no"
headers = {'User-Agent': user_agent}
# Empty list for weather data # Empty list for weather data
weather_data = [] weather_data = []
resp_code = 500 status_code = 500
# Request weather data for each coordinate pair # Request weather data for each coordinate pair
for coord in coordinates: for coord in coordinates:
lat = coord.get('lat') lat = round(coord.get('lat'), 4) # YR API only allows for up to 4 decimal points
lng = coord.get('lng') lng = round(coord.get('lng'), 4)
# Construct request string and execute get request to Yr API # Construct request string and execute get request to Yr API
url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={lat}&lon={lng}" url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={lat}&lon={lng}"
response = requests.get(url) response = requests.get(url, headers=headers)
if response.status_code == 200: if response.status_code == 200:
if status_code != 200:
status_code = 200
data = response.json() # Extract data from response data = response.json() # Extract data from response
timeseries = data['properties']['timeseries'] timeseries = data['properties']['timeseries']
# Get data for current time and append to weather_data # Get data for current time and append to weather_data
for entry in timeseries: for entry in timeseries:
if entry['time'] == current_time: if entry['time'] == current_time_str:
data = entry['data']['instant']['details']
temperature = data['air_temperature']
humidity = data['relative_humidity']
weather_object = { weather_object = {
'Latitude': lat, 'Latitude': lat,
'Longitude': lng, 'Longitude': lng,
'Temperature': entry['temperature'], 'Temperature': temperature,
'Humidity': entry['humidity'] 'Humidity': humidity
} }
# Append weather_object to weather_data list # Append weather_object to weather_data list
weather_data.append(weather_object) weather_data.append(weather_object)
break break
if resp_code == 500:
resp_code = 200
else: # Add error message if no weather data is found or the request fails else: # Add error message if no weather data is found or the request fails
weather_data.append({'message': 'No data found', 'latitude': lat, 'longitude': lng}) print(f"Request to weather API failed with status code {response.status_code}")
status_code = response.status_code
# Set headers # Set headers
self.send_response(resp_code) self.send_response(status_code)
self.send_header("Content-type", "application/json") self.send_header("Content-type", "application/json")
self.end_headers() self.end_headers()
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment