From afef86c59c3190669fe08db0f3e2f30a2200b6c5 Mon Sep 17 00:00:00 2001 From: Nico Melone Date: Wed, 22 Jan 2025 09:36:50 -0600 Subject: [PATCH] added a weather page with api requests --- app.py | 33 +++++++++++++++++++++++++++++++++ templates/base.html | 1 + templates/weather.html | 8 ++++++++ 3 files changed, 42 insertions(+) create mode 100644 templates/weather.html diff --git a/app.py b/app.py index b9854c9..b687dbc 100644 --- a/app.py +++ b/app.py @@ -1,6 +1,7 @@ from flask import Flask, render_template, request, redirect, url_for from models import db, Item from datetime import datetime as dt +import requests app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///items.db' @@ -36,5 +37,37 @@ def add_item(): @app.route('/about') def about(): return render_template('about.html', now=dt.now()) + +@app.route('/weather') +def get_weather(): + # Replace with your API's URL + api_url = "https://api.open-meteo.com/v1/forecast?latitude=32.0015&longitude=-102.1394¤t_weather=true" + + try: + # Make the GET request to the API + response = requests.get(api_url) + + # Check if the request was successful + response.raise_for_status() # Raises an HTTPError for bad responses + + # Parse the JSON response + weather_data = response.json() + + # Extract relevant information + units = weather_data.get('current_weather_units', {}) + current_weather = weather_data.get('current_weather', {}) + temperature = current_weather.get('temperature', 'N/A') + temperature_unit = units.get('temperature', "") + wind_speed = current_weather.get('windspeed', 'N/A') + wind_speed_unit = units.get('windspeed', "") + wind_direction = current_weather.get('winddirection', 'N/A') + wind_direction_unit = units.get('winddirection', "") + # Pass the data to the template + return render_template('weather.html', temperature=temperature, wind_speed=wind_speed, temperature_unit=temperature_unit, wind_speed_unit=wind_speed_unit, wind_direction=wind_direction,wind_direction_unit=wind_direction_unit ) + + except requests.exceptions.RequestException as e: + # Handle errors + return f"An error occurred: {e}" + if __name__ == '__main__': app.run(debug=True) diff --git a/templates/base.html b/templates/base.html index d54cd5a..f40ed5b 100644 --- a/templates/base.html +++ b/templates/base.html @@ -11,6 +11,7 @@ diff --git a/templates/weather.html b/templates/weather.html new file mode 100644 index 0000000..0c455c8 --- /dev/null +++ b/templates/weather.html @@ -0,0 +1,8 @@ +{% extends "base.html" %} + +{% block content %} +

Current Weather

+

Temperature: {{ temperature }} {{ temperature_unit }} | {{(temperature * 9/5) + 32}}°F

+

Wind Speed: {{ wind_speed }} {{ wind_speed_unit }}

+

Wind Direction: {{ wind_direction }} {{ wind_direction_unit }}

+{% endblock %} \ No newline at end of file