From 2cc1fcd91811498c46efe560a28a5bdf3349e00b Mon Sep 17 00:00:00 2001 From: Tyler Perkins Date: Mon, 13 Nov 2023 20:21:25 -0500 Subject: [PATCH] Add weather endpoint --- src/config.yaml | 2 ++ src/main.py | 3 ++- src/routers/images.py | 1 - src/routers/weather.py | 45 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 src/routers/weather.py diff --git a/src/config.yaml b/src/config.yaml index 108c433..be6bfb5 100644 --- a/src/config.yaml +++ b/src/config.yaml @@ -6,3 +6,5 @@ images: endpoint: s3.clortox.com bucket: backgrounds secure: True +weather: + period: 15 diff --git a/src/main.py b/src/main.py index 9691259..4c0de6f 100644 --- a/src/main.py +++ b/src/main.py @@ -1,9 +1,10 @@ from datetime import datetime, date from fastapi import FastAPI, HTTPException -from routers import recipe, images +from routers import recipe, images, weather app = FastAPI() app.include_router(recipe.router) app.include_router(images.router) +app.include_router(weather.router) diff --git a/src/routers/images.py b/src/routers/images.py index 49c23d7..1993d56 100644 --- a/src/routers/images.py +++ b/src/routers/images.py @@ -77,7 +77,6 @@ async def background(): return file_response - except Exception as err: traceback.print_exc() raise HTTPException(status_code=500, detail=f"Unknown error. Check logs {err}") diff --git a/src/routers/weather.py b/src/routers/weather.py new file mode 100644 index 0000000..7346fd3 --- /dev/null +++ b/src/routers/weather.py @@ -0,0 +1,45 @@ +from fastapi import APIRouter, Depends, HTTPException, Header, BackgroundTasks +from fastapi.responses import FileResponse, Response + +from typing import List, Optional +from pydantic import BaseModel +import logging +from config import getConfig + +import os +from datetime import datetime, timedelta +import requests + + +router = APIRouter( + prefix="/weather", + tags=["Weather"], + responses={404: {"description": "Not found"}} + ) + +weather = None +last_checked_time = None + +interval = timedelta(minutes=getConfig()["weather.period"]) + +def getWeather(location: str = "Stow") -> str: + global last_checked_time + global weather + + if last_checked_time is None: + last_checked_time = datetime(1970, 1, 1) + + if datetime.now() - last_checked_time >= timedelta(seconds=5): + print("Making request for weather") + weather = requests.get(f"https://wttr.in/{location}?format=1") + last_checked_time = datetime.now() + + return weather.content; + +@router.get("/now") +def get_weather_now_in_stow(): + """ + Obtain the current weather in Stow, Ohio + """ + + return getWeather()