Files
flask-practice/app.py
2025-03-17 19:30:50 -05:00

108 lines
3.7 KiB
Python

from flask import Flask, render_template, request, redirect, url_for, jsonify
from models import db, Item
from datetime import datetime as dt
import requests, csv
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///items.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db.init_app(app)
@app.before_request
def initialize_app():
if not hasattr(app, 'is_initialized'):
db.create_all()
app.is_initialized = True
@app.route('/')
def home():
items = Item.query.all()
testList = [1,2,3,"Apple"]
username = "Test_Username"
return render_template('home.html', items=items, testList=testList, username=username)
@app.route('/relative-rank')
def rank():
return render_template('relative_rank.html')
@app.route("/save-rankings", methods=["POST"])
def save_rankings():
data = request.json # Get the ranked items and tiers
print(data) # For debugging, print the data received
return jsonify({"message": "Rankings saved successfully!"})
@app.route('/add', methods=['GET', 'POST'])
def add_item():
if request.method == 'POST':
name = request.form['name']
description = request.form['description']
new_item = Item(name=name, description=description)
db.session.add(new_item)
db.session.commit()
return redirect(url_for('home'))
return render_template('add_item.html')
@app.route('/motion')
def motion():
return render_template('motion.html')
@app.route('/about')
def about():
return render_template('about.html', now=dt.now())
@app.route('/short_stories')
def short_stories():
return render_template('short_stories.html')
@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}"
def load_vocab(csv_filename):
vocab_list = []
with open(csv_filename, newline='', encoding='utf-8') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
hiragana_katakana, kanji, english = row
japanese = kanji if kanji else hiragana_katakana # Use kanji if available, otherwise use kana
vocab_list.append((japanese, english))
return vocab_list
@app.route('/vocabulary')
def vocabulary():
vocab_list = load_vocab('static/vocab.csv') # Ensure your CSV is in the 'static' folder
return render_template('vocabulary.html', vocab_list=vocab_list)
if __name__ == '__main__':
app.run(debug=True)