caching
This commit is contained in:
parent
fc964d3ac4
commit
5d4937e57a
4 changed files with 68 additions and 2 deletions
23
main.py
23
main.py
|
@ -7,6 +7,7 @@ import pprint
|
|||
import zoneinfo
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from cachetools import TTLCache
|
||||
import httpx
|
||||
|
||||
|
||||
|
@ -16,6 +17,9 @@ eastern = zoneinfo.ZoneInfo("America/New_York")
|
|||
|
||||
app = FastAPI()
|
||||
|
||||
# Initialize caches for 15 minutes
|
||||
weather_cache = TTLCache(maxsize=100, ttl=900) # 15 minutes
|
||||
pollen_cache = TTLCache(maxsize=100, ttl=900) # 15 minutes
|
||||
|
||||
CONFIG = {
|
||||
# salem, ma
|
||||
|
@ -89,6 +93,10 @@ def fallback_handler(func):
|
|||
|
||||
@fallback_handler
|
||||
async def fetch_pollen(zipcode):
|
||||
# Check the cache first
|
||||
if zipcode in pollen_cache:
|
||||
return pollen_cache[zipcode]
|
||||
|
||||
url = f"https://www.pollen.com/api/forecast/current/pollen/{zipcode}"
|
||||
headers = {
|
||||
"User-Agent": (
|
||||
|
@ -104,7 +112,7 @@ async def fetch_pollen(zipcode):
|
|||
response = await client.get(url, headers=headers)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
return [
|
||||
result = [
|
||||
{
|
||||
"forecast_date": format_datetime(
|
||||
datetime.fromisoformat(data["ForecastDate"])
|
||||
|
@ -119,17 +127,25 @@ async def fetch_pollen(zipcode):
|
|||
],
|
||||
}
|
||||
]
|
||||
# Cache the result
|
||||
pollen_cache[zipcode] = result
|
||||
return result
|
||||
|
||||
|
||||
@fallback_handler
|
||||
async def fetch_weather(lat, lon, weather_api_key):
|
||||
# Check the cache first
|
||||
cache_key = (lat, lon)
|
||||
if cache_key in weather_cache:
|
||||
return weather_cache[cache_key]
|
||||
|
||||
url = f"https://api.openweathermap.org/data/3.0/onecall?lat={lat}&lon={lon}&appid={weather_api_key}&units=imperial"
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(url)
|
||||
response.raise_for_status()
|
||||
data = response.json()
|
||||
current, periods = data["current"], data["daily"][:2]
|
||||
return [
|
||||
result = [
|
||||
{
|
||||
"forecast_date": format_datetime(datetime.fromtimestamp(current["dt"])),
|
||||
"current_temp": int(round(current["temp"])),
|
||||
|
@ -154,6 +170,9 @@ async def fetch_weather(lat, lon, weather_api_key):
|
|||
],
|
||||
}
|
||||
]
|
||||
# Cache the result
|
||||
weather_cache[cache_key] = result
|
||||
return result
|
||||
|
||||
|
||||
@app.get("/")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue