added a weather page with api requests

This commit is contained in:
Nico Melone
2025-01-22 09:36:50 -06:00
parent 5b214b9978
commit afef86c59c
3 changed files with 42 additions and 0 deletions

33
app.py
View File

@@ -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&current_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)

View File

@@ -11,6 +11,7 @@
<nav>
<a href="{{ url_for('home') }}">Home</a>
<a href="{{ url_for('add_item') }}">Add Item</a>
<a href="{{ url_for('get_weather') }}">Weather</a>
<a href="{{ url_for('about') }}">About</a>
</nav>
</header>

8
templates/weather.html Normal file
View File

@@ -0,0 +1,8 @@
{% extends "base.html" %}
{% block content %}
<h1>Current Weather</h1>
<p>Temperature: {{ temperature }} {{ temperature_unit }} | {{(temperature * 9/5) + 32}}°F</p>
<p>Wind Speed: {{ wind_speed }} {{ wind_speed_unit }}</p>
<p>Wind Direction: {{ wind_direction }} {{ wind_direction_unit }}</p>
{% endblock %}