From f5e25b58ca4aa949930a23c118496f7e85b39241 Mon Sep 17 00:00:00 2001 From: Muskankr Date: Mon, 13 Jul 2026 11:19:00 +0530 Subject: [PATCH] Add caching to /weather endpoint to reduce API calls --- backend/__init__.py | 13 ++++++++++++- backend/alertsystem.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/backend/__init__.py b/backend/__init__.py index c6077fd..b533b3f 100644 --- a/backend/__init__.py +++ b/backend/__init__.py @@ -1,2 +1,13 @@ # intentionally left empty — makes backend a package for making -# it as importable from the outside \ No newline at end of file +# it as importable from the outside + +from flask import Flask +from flask_caching import Cache + +app = Flask(__name__) + +# Simple in‑memory cache, 5 min default timeout +cache = Cache(app, config={'CACHE_TYPE': 'SimpleCache', 'CACHE_DEFAULT_TIMEOUT': 300}) + +# Import routes after app + cache are ready +from backend import alertsystem diff --git a/backend/alertsystem.py b/backend/alertsystem.py index bde3472..4c9ecab 100644 --- a/backend/alertsystem.py +++ b/backend/alertsystem.py @@ -2,6 +2,8 @@ import sys import requests +from flask import request, jsonify +from backend import app, cache from dotenv import load_dotenv load_dotenv() @@ -107,6 +109,36 @@ def frontend_files(filename): CYCLONE_RISK_THRESHOLD = 0.60 DROUGHT_RISK_THRESHOLD = 0.70 + +OPENWEATHER_API_KEY = "YOUR_KEY" + +@app.route("/weather") +def weather(): + city = request.args.get("city") + state = request.args.get("state") + country = request.args.get("country") + + if not city or not country: + return jsonify({"error": "Missing required fields"}), 400 + + # Build cache key + cache_key = f"weather:{city}:{state}:{country}" + + # Check cache first + cached = cache.get(cache_key) + if cached: + return jsonify(cached) + + # If not cached, call OpenWeatherMap + url = f"http://api.openweathermap.org/data/2.5/weather?q={city},{state},{country}&appid={OPENWEATHER_API_KEY}" + resp = requests.get(url) + data = resp.json() + + # Store in cache + cache.set(cache_key, data) + + return jsonify(data) + # ========================================================= # GET LOCATION COORDINATES (Nominatim / OpenStreetMap) # =========================================================