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

add: get_weather()

parent b51335e7
No related branches found
No related tags found
No related merge requests found
from flask import request
import requests
import datetime
import json
# get_weather retrieves weather data for a given set of coordinates
def get_weather():
# Extract url parameters
latitude = request.args.get('lat', '')
longitude = request.args.get('lon', '')
# Form timestamp string with correct format
current_time = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ")
# Construct request string and execute get request to Yr API
url = f"https://api.met.no/weatherapi/locationforecast/2.0/compact?lat={latitude}&lon={longitude}"
response = requests.get(url)
if response.status_code == 200: # Extract data from response
data = response.json()
timeseries = data['properties']['timeseries']
# Get data for current time
weather_data = None
for entry in timeseries:
if entry['time'] == current_time:
weather_data = entry['data']
break
if weather_data is not None:
resp_code = 200
else:
resp_code = 404 # Data for current time not found
weather_data = {}
else: # Write empty data object and return status code 500
resp_code = 500
weather_data = {}
return json.dumps(weather_data), resp_code
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