from datetime import date import requests from decimal import Decimal # Import your database model and the session from your database configuration from app.models.auto import Auto_Temp from database import session def Average(lst): """Calculates the average of a list of numbers.""" return sum(lst) / len(lst) def fetch_and_store_daily_temp() -> bool: """ Fetches the current day's weather for Worcester, MA, calculates the Heating Degree Day (HDD), and stores it in the database if it doesn't already exist. Returns: bool: True if the temperature is successfully fetched and stored (or already exists), False if an error occurs. """ # 1. Check if the temperature for today already exists in the database today = date.today() if session.query(Auto_Temp).filter(Auto_Temp.todays_date == today).first(): print(f"Temperature for {today} already exists in the database. Skipping fetch.") return True # 2. If it doesn't exist, fetch it from the API print(f"Fetching temperature for {today} from OpenWeatherMap...") try: # API key and location api_key = '21648d8c8d1a4ae495ace0b7810b4d36' location = 'Worcester,US' # Make request to OpenWeatherMap Current Weather API with imperial units for Fahrenheit url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=imperial" response = requests.get(url) response.raise_for_status() # Raise an error for bad status codes data = response.json() # Extract temperatures in Fahrenheit main = data.get('main', {}) current_temp = Decimal(main.get('temp', 0)) low_temp = Decimal(main.get('temp_min', 0)) high_temp = Decimal(main.get('temp_max', 0)) # Calculate average temperature and Heating Degree Days (HDD) avg_temp = (low_temp + high_temp) / 2 # HDD is based on a baseline of 65°F. It cannot be negative for heating calculations. degree_day = max(Decimal(0), 65 - avg_temp) # 3. Create a new database object add_new_temp = Auto_Temp( temp=current_temp, temp_max=high_temp, temp_min=low_temp, temp_avg=round(avg_temp, 2), degree_day=round(degree_day), todays_date=today ) # 4. Add the new record to the session (it will be committed by the calling function) session.add(add_new_temp) print(f"Successfully fetched and staged temperature for {today}.") return True except Exception as e: print(f"An error occurred while fetching weather data: {e}") # Make sure to rollback the session in case of a partial failure session.rollback() return False