from flask import Flask, request, jsonify from flask_cors import CORS from flask_limiter import Limiter from flask_limiter.util import get_remote_address import requests import time app = Flask(__name__) CORS(app) # Rate Limiter Configuration # 1000 per day (Hard limit), 60 per hour, 5 per minute per IP limiter = Limiter( get_remote_address, app=app, default_limits=["1000 per day", "60 per hour", "10 per minute"], storage_uri="memory://" ) API_KEY = "0a4f51067c3f1588b9e0c0fa4b313986" BASE_URL = "https://api.openweathermap.org/data/2.5" # Simple In-Memory Cache to save API calls # key: city_name, value: {timestamp, data} weather_cache = {} CACHE_DURATION = 600 # 10 minutes @app.route('/weather', methods=['GET']) @limiter.limit("1000 per day") def get_weather(): city = request.args.get('city') if not city: return jsonify({'error': 'City is required'}), 400 city = city.lower().strip() # Check Cache current_time = time.time() if city in weather_cache: cached_data, timestamp = weather_cache[city] if current_time - timestamp < CACHE_DURATION: return jsonify({**cached_data, 'source': 'cache'}) # Fetch from OpenWeather try: response = requests.get(f"{BASE_URL}/weather", params={ 'q': city, 'appid': API_KEY, 'units': 'metric' }) if response.status_code != 200: return jsonify({'error': 'City not found'}), response.status_code data = response.json() # Save to Cache weather_cache[city] = (data, current_time) return jsonify({**data, 'source': 'api'}) except Exception as e: return jsonify({'error': str(e)}), 500 @app.route('/health', methods=['GET']) def health(): return jsonify({'status': 'online', 'limit': '1000/day'}) if __name__ == '__main__': import os port = int(os.environ.get('PORT', 7860)) app.run(host='0.0.0.0', port=port)